-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathforward_mode.py
More file actions
51 lines (37 loc) · 1.08 KB
/
forward_mode.py
File metadata and controls
51 lines (37 loc) · 1.08 KB
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
import math
def type_checker(f):
def inner(self, other):
return f(self, other) if isinstance(other, Dual) else f(self, Dual(other, 0))
return inner
class Dual:
def __init__(self, u, du=1):
self.u = u
self.du = du
def __str__(self):
return f"({self.u}, {self.du})"
def __pos__(self):
return self
def __neg__(self):
return Dual(-self.u, -self.du)
# @type_checker
def __add__(self, other):
return Dual(self.u+other.u, self.du+other.du)
# @type_checker
def __sub__(self, other):
return self+(-other)
# @type_checker
def __mul__(self, other):
return Dual(self.u*other.u, self.u*other.du+self.du*other.u)
# @type_checker
def __truediv__(self, other):
return Dual(self.u/other.u, (other.u*self.du - self.u*other.du)/(other.u**2))
def __pow__(self, n):
return Dual(self.u**n, n*self.u**(n-1)*self.du)
def dual_sin(self):
if not isinstance(self, Dual):
return math.sin(self)
return Dual(math.sin(self.u), math.cos(self.u)*self.du)
def dual_cos(self):
if not isinstance(self, Dual):
return math.cos(self)
return Dual(math.cos(self.u), math.sin(self.u)*self.du)