-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathForwardMode.py
49 lines (29 loc) · 881 Bytes
/
ForwardMode.py
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
#%%
import __init__
from DualNumber import DualNumber
from MathLib.FunctionWrapper import Function
from MathLib.Functions import sin, cos, tan, log, exp
#%%
def f(x, y):
return sin(x)*y + 7*(x*x)
a = (2, 4)
x = DualNumber(a[0], 1) # a_1 + epsilon
y = DualNumber(a[1], 0) # a_2
dx = f(x, y)
x = DualNumber(a[0], 0) # a_1
y = DualNumber(a[1], 1) # a_2 + epsilon
dy = f(x, y)
val = (dx.primal, dy.primal) # dx.primal = dy.primal
grad = (dx.tangent, dy.tangent)
print("value f at ", a, "=", val)
print("grad f at a", a, "=", grad)
# Example : Directionnal derivative
a = (2, 4)
v = (7, 3)
x = DualNumber(a[0], v[0]) # a_1 + v_1*epsilon
y = DualNumber(a[1], v[1]) # a_2 + v_2*epsilon
d_v = f(x, y) # directionnal derivative
print("-"*5)
print("value f at ", a, "=", d_v.primal)
print("directionnal derivative f at ", a, "for direction ", v, "=", d_v.tangent)
#%%