ForwardDiff Answers

Problem 1

In [1]:
f(x) = x^5 + 3x^2
using ForwardDiff
fprime(x) = ForwardDiff.derivative(f,x)
Out[1]:
fprime (generic function with 1 method)
In [2]:
using Plots; gr()
x = -5:0.1:5
plot(x,fprime.(x))
Out[2]:
-4 -2 0 2 4 0 1000 2000 3000 y1
In [3]:
plot!(x,5x.^4+6x)
Out[3]:
-4 -2 0 2 4 0 1000 2000 3000 y1 y2

Problem 2

In [5]:
using LinearAlgebra
function spherical2Cartesian(coordinates)
    r, θ, ϕ = coordinates
    x = r*sin(θ)*cos(ϕ)
    y = r*sin(θ)*sin(ϕ)
    z = r*cos(θ)
    [x, y, z]
end

ρ, θ, ϕ = 2.5, π/4, π/2
coordinates = [ρ, θ, ϕ]
J = ForwardDiff.jacobian(spherical2Cartesian, coordinates)
detJ = det(J)

det_analytical = ρ^2 * sin(θ)
det_analytical  detJ
Out[5]:
true