Advertisement
Guest User

dual.nim

a guest
Mar 10th, 2021
362
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.25 KB | None | 0 0
  1.  
  2. # Dual numbers for automatic differentiation
  3. #
  4. # (c) 2018-2021 [email protected] (Ian Smith), for licencing see the LICENCE file
  5.  
  6. import math
  7.  
  8. type Dual* = tuple[val: float, dot: float]
  9.  
  10. func d_dual*(x: float): Dual =
  11. (x, 0.0)
  12.  
  13. func d_var*(x: float): Dual =
  14. (x, 1.0)
  15.  
  16. func `+`*(x, y: Dual): Dual =
  17. (x.val + y.val, x.dot + y.dot)
  18.  
  19. func `+`*(x: Dual, y: float): Dual =
  20. (x.val + y, x.dot)
  21.  
  22. func `+`*(x: float, y: Dual): Dual =
  23. (x + y.val, y.dot)
  24.  
  25. func `-`*(x, y: Dual): Dual =
  26. (x.val - y.val, x.dot - y.dot)
  27.  
  28. func `-`*(x: Dual, y: float): Dual =
  29. (x.val - y, x.dot)
  30.  
  31. func `-`*(x: float, y: Dual): Dual =
  32. (x - y.val, - y.dot)
  33.  
  34. func `*`*(x, y: Dual): Dual =
  35. (x.val * y.val, x.val * y.dot + x.dot * y.val)
  36.  
  37. func `*`*(x: Dual, y: float): Dual =
  38. (x.val * y, x.dot * y)
  39.  
  40. func `*`*(x: float, y: Dual): Dual =
  41. (x * y.val, x * y.dot)
  42.  
  43. func `/`*(x, y: Dual): Dual =
  44. (x.val / y.val, (x.dot * y.val - x.val * y.dot) / (y.val * y.val))
  45.  
  46. func `/`*(x: Dual, y: float): Dual =
  47. (x.val / y, x.dot / y)
  48.  
  49. func `/`*(x: float, y: Dual): Dual =
  50. (x / y.val, - y.dot * x / (y.val * y.val))
  51.  
  52. func sin*(x: Dual): Dual =
  53. (sin(x.val), x.dot * cos(x.val))
  54.  
  55. func cos*(x: Dual): Dual =
  56. (cos(x.val), - x.dot * sin(x.val))
  57.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement