Skip to content

Commit 16417ec

Browse files
authored
Merge pull request #657 from cossio/doc
example in docs
2 parents e3670ce + e76c727 commit 16417ec

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed

docs/src/index.md

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,4 +12,54 @@ ForwardDiff is a registered Julia package, so it can be installed by running:
1212
julia> Pkg.add("ForwardDiff")
1313
```
1414

15+
Here's a simple example showing the package in action:
16+
17+
```julia
18+
julia> using ForwardDiff
19+
20+
julia> f(x::Vector) = sin(x[1]) + prod(x[2:end]); # returns a scalar
21+
22+
julia> x = vcat(pi/4, 2:4)
23+
4-element Vector{Float64}:
24+
0.7853981633974483
25+
2.0
26+
3.0
27+
4.0
28+
29+
julia> ForwardDiff.gradient(f, x)
30+
4-element Vector{Float64}:
31+
0.7071067811865476
32+
12.0
33+
8.0
34+
6.0
35+
36+
julia> ForwardDiff.hessian(f, x)
37+
4×4 Matrix{Float64}:
38+
-0.707107 0.0 0.0 0.0
39+
0.0 0.0 4.0 3.0
40+
0.0 4.0 0.0 2.0
41+
0.0 3.0 2.0 0.0
42+
```
43+
44+
Functions like `f` which map a vector to a scalar are the best case for reverse-mode automatic differentiation,
45+
but ForwardDiff may still be a good choice if `x` is not too large, as it is much simpler.
46+
The best case for forward-mode differentiation is a function which maps a scalar to a vector, like this `g`:
47+
48+
```julia
49+
julia> g(y::Real) = [sin(y), cos(y), tan(y)]; # returns a vector
50+
51+
julia> ForwardDiff.derivative(g, pi/4)
52+
3-element Vector{Float64}:
53+
0.7071067811865476
54+
-0.7071067811865475
55+
1.9999999999999998
56+
57+
julia> ForwardDiff.jacobian(x) do x # anonymous function, returns a length-2 vector
58+
[sin(x[1]), prod(x[2:end])]
59+
end
60+
2×4 Matrix{Float64}:
61+
0.707107 0.0 0.0 0.0
62+
0.0 12.0 8.0 6.0
63+
```
64+
1565
If you find ForwardDiff useful in your work, we kindly request that you cite [our paper](https://arxiv.org/abs/1607.07892). The relevant [BibLaTex is available in ForwardDiff's README](https://github.com/JuliaDiff/ForwardDiff.jl#publications) (not included here because BibLaTex doesn't play nice with Documenter/Jekyll).

0 commit comments

Comments
 (0)