numerics.nbt 952 B

123456789101112131415161718192021222324252627282930313233343536
  1. use numerics::solve
  2. use numerics::diff
  3. use numerics::fixed_point
  4. # Root finding
  5. fn f1(x) = x³ - x - 2
  6. assert_eq(root_bisect(f1, 1, 2, 1e-10, 1e-10), 1.52137970680, 1e-8)
  7. fn f1_prime(x) = 3 x² - 1
  8. assert_eq(root_newton(f1, f1_prime, 1, 1e-10), 1.52137970680, 1e-8)
  9. assert_eq(root_newton(f1, f1_prime, 2, 1e-10), 1.52137970680, 1e-8)
  10. # Fixed point iteration
  11. let a = 3
  12. fn f_sqrt3(x: Scalar) = 0.5 * (a / x + x)
  13. assert_eq(fixed_point(f_sqrt3, 1, 1e-10), sqrt(3), 1e-10)
  14. # Differentiation
  15. assert_eq(diff(log, 2.0), 0.5, 1e-5)
  16. # TODO: Sadly, the following is not possible at the moment. See https://github.com/sharkdp/numbat/issues/521 for details
  17. # assert_eq(diff(sin, 0.0), 1.0, 1e-5)
  18. assert_eq(diff(sqrt, 1.0), 0.5, 1e-5)
  19. fn f2(x: Scalar) -> Scalar = x² + 4 x + 1
  20. assert_eq(diff(f2, 2.0), 8.0, 1e-5)
  21. fn dist(t: Time) -> Length = 0.5 g0 t^2
  22. fn velocity(t: Time) -> Velocity = diff(dist, t)
  23. assert_eq(velocity(2.0 s), 2.0 s × g0, 1e-3 m/s)