-
Notifications
You must be signed in to change notification settings - Fork 77
/
Copy pathderivative.jl
62 lines (49 loc) · 2.06 KB
/
derivative.jl
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
#
# derivative()
#
f1(x::Real) = sin(x)
@test norm(derivative(f1, :scalar, :forward)(0.0) - cos(0.0)) < 10e-4
@test norm(derivative(f1, :scalar, :central)(0.0) - cos(0.0)) < 10e-4
@test norm(derivative(f1, :forward)(0.0) - cos(0.0)) < 10e-4
@test norm(derivative(f1, :central)(0.0) - cos(0.0)) < 10e-4
@test norm(derivative(f1)(0.0) - cos(0.0)) < 10e-4
f2(x::AbstractVector) = sin(x[1])
@test norm(derivative(f2, :vector, :forward)([0.0]) .- cos(0.0)) < 10e-4
@test norm(derivative(f2, :vector, :central)([0.0]) .- cos(0.0)) < 10e-4
# Test functionality for SubArrays
@test norm(derivative(f2, :vector, :forward)(sub([0.0],:)) .- cos(0.0)) < 10e-4
@test norm(derivative(f2, :vector, :central)(sub([0.0],:)) .- cos(0.0)) < 10e-4
#
# ctranspose overloading
#
f3(x::Real) = sin(x)
for x in linspace(0.0, 0.1, 11) # seq()
@test norm(f3'(x) - cos(x)) < 10e-4
end
#
# gradient()
#
f4(x::AbstractVector) = (100.0 - x[1])^2 + (50.0 - x[2])^2
@test norm(Calculus.gradient(f4, :forward)([100.0, 50.0]) - [0.0, 0.0]) < 10e-4
@test norm(Calculus.gradient(f4, :central)([100.0, 50.0]) - [0.0, 0.0]) < 10e-4
@test norm(Calculus.gradient(f4)([100.0, 50.0]) - [0.0, 0.0]) < 10e-4
# Test for SubArrays
@test norm(Calculus.gradient(f4, :forward)(sub([100.0, 50.0],:)) - [0.0, 0.0]) < 10e-4
@test norm(Calculus.gradient(f4, :central)(sub([100.0, 50.0],:)) - [0.0, 0.0]) < 10e-4
@test norm(Calculus.gradient(f4)(sub([100.0, 50.0],:)) - [0.0, 0.0]) < 10e-4
#
# second_derivative()
#
@test norm(second_derivative(x -> x^2)(0.0) - 2.0) < 10e-4
@test norm(second_derivative(x -> x^2)(1.0) - 2.0) < 10e-4
@test norm(second_derivative(x -> x^2)(10.0) - 2.0) < 10e-4
@test norm(second_derivative(x -> x^2)(100.0) - 2.0) < 10e-4
#
# hessian()
#
f5(x) = sin(x[1]) + cos(x[2])
@test norm(Calculus.gradient(f5)([0.0, 0.0]) - [cos(0.0), -sin(0.0)]) < 10e-4
@test norm(hessian(f5)([0.0, 0.0]) - [-sin(0.0) 0.0; 0.0 -cos(0.0)]) < 10e-4
# And for SubArrays again
@test norm(Calculus.gradient(f5)(sub([0.0, 0.0],:)) - [cos(0.0), -sin(0.0)]) < 10e-4
@test norm(hessian(f5)(sub([0.0, 0.0],:)) - [-sin(0.0) 0.0; 0.0 -cos(0.0)]) < 10e-4