Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Dual numbers for automatic differentiation
- #
- # (c) 2018-2021 [email protected] (Ian Smith), for licencing see the LICENCE file
- import math
- type Dual* = tuple[val: float, dot: float]
- func d_dual*(x: float): Dual =
- (x, 0.0)
- func d_var*(x: float): Dual =
- (x, 1.0)
- func `+`*(x, y: Dual): Dual =
- (x.val + y.val, x.dot + y.dot)
- func `+`*(x: Dual, y: float): Dual =
- (x.val + y, x.dot)
- func `+`*(x: float, y: Dual): Dual =
- (x + y.val, y.dot)
- func `-`*(x, y: Dual): Dual =
- (x.val - y.val, x.dot - y.dot)
- func `-`*(x: Dual, y: float): Dual =
- (x.val - y, x.dot)
- func `-`*(x: float, y: Dual): Dual =
- (x - y.val, - y.dot)
- func `*`*(x, y: Dual): Dual =
- (x.val * y.val, x.val * y.dot + x.dot * y.val)
- func `*`*(x: Dual, y: float): Dual =
- (x.val * y, x.dot * y)
- func `*`*(x: float, y: Dual): Dual =
- (x * y.val, x * y.dot)
- func `/`*(x, y: Dual): Dual =
- (x.val / y.val, (x.dot * y.val - x.val * y.dot) / (y.val * y.val))
- func `/`*(x: Dual, y: float): Dual =
- (x.val / y, x.dot / y)
- func `/`*(x: float, y: Dual): Dual =
- (x / y.val, - y.dot * x / (y.val * y.val))
- func sin*(x: Dual): Dual =
- (sin(x.val), x.dot * cos(x.val))
- func cos*(x: Dual): Dual =
- (cos(x.val), - x.dot * sin(x.val))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement