complex.lisp 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. (import math/numerics ())
  2. (import math/complex ())
  3. (import test ())
  4. (defgeneric req? (a b))
  5. (defmethod (req? number number) (a b)
  6. (< (math/abs (- a b)) 1e-5))
  7. (defmethod (req? complex complex) (a b)
  8. (and (req? (real a) (real b)) (req? (imaginary a) (imaginary b))))
  9. (describe "The math library has complex numbers which"
  10. (can "be created and destructured"
  11. (check [(number a) (number b)]
  12. (eq? a (real (complex a b)))
  13. (eq? b (imaginary (complex a b)))))
  14. (can "be pretty printed"
  15. (affirm (eq? "2+3i" (pretty (complex 2 3)))
  16. (eq? "2-3i" (pretty (complex 2 -3)))
  17. (eq? "-2+3i" (pretty (complex -2 3)))
  18. (eq? "-2-3i" (pretty (complex -2 -3)))))
  19. (can "be equated"
  20. (affirm (eq? (complex 1 2) (complex 1 2))
  21. (neq? (complex 1 2) (complex 1 3))
  22. (neq? (complex 1 2) (complex 2 2))
  23. (eq? (complex 1 0) 1)
  24. (neq? (complex 1 1) 1)
  25. (eq? 1 (complex 1 0)
  26. (neq? 1 (complex 1 1)))))
  27. (can "be added"
  28. (affirm (eq? (complex 12 15) (n+ (complex 4 5) (complex 8 10)))
  29. (eq? (complex 5 1) (n+ (complex 3 1) 2))
  30. (eq? (complex 5 1) (n+ 2 (complex 3 1)))))
  31. (can "be subtracted"
  32. (affirm (eq? (complex 8 10) (n- (complex 12 15) (complex 4 5)))
  33. (eq? (complex 3 1) (n- (complex 5 1) 2))
  34. (eq? (complex 3 -1) (n- 5 (complex 2 1)))))
  35. (can "be multiplied"
  36. (affirm (eq? (complex -13 11) (n* (complex 1 3) (complex 2 5)))
  37. (eq? (complex 2 6) (n* (complex 1 3) 2))
  38. (eq? (complex 2 6) (n* 2 (complex 1 3)))))
  39. (can "be divided"
  40. (affirm (eq? (complex 1.0 1.0) (n/ (complex 1 3) (complex 2 1)))
  41. (eq? (complex 20/13 9/13) (n/ (complex 1/1 6/1) (complex 2/1 3/1)))
  42. (eq? (complex 2/3 1) (n/ (complex 2 3) 3/1))
  43. (eq? (complex 0.3 -0.9) (n/ 3 (complex 1 3)))))
  44. (can "be raised to some power"
  45. (affirm (req? (complex 0 2) (nexpt (complex 1 1) 2))))
  46. (can "be conjugated"
  47. (check [(number a) (number b)]
  48. (eq? (complex a (nnegate b)) (conjugate (complex a b)))))
  49. (can "be converted to polar coordinates"
  50. (affirm (eq? 5 (first (->polar (complex 3 4))))
  51. (eq? 45 (math/deg (second (->polar (complex 2 2)))))))
  52. (can "be created from polar coordinates"
  53. (with (c (polar-> 5 0.92729521800161))
  54. (affirm (req? (complex 3 4) c))))
  55. (it "has an identity between ->polar and polar->"
  56. (check [(number a) (number b)]
  57. (req? (complex a b) (polar-> (->polar (complex a b))))))
  58. )