polynomial_roots.sf 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. #!/usr/bin/ruby
  2. # Find all the roots `x` to a given polynomial `f`, such that f(x) = 0, using Newton's method.
  3. func newton_inverse_method(f, x = 1f) {
  4. var df = derivative(f)
  5. while (f(x) <~> 0) {
  6. x = (x - (f(x) / df(x)))
  7. }
  8. return x
  9. }
  10. func roots_of_unity(n) {
  11. n.of { |j|
  12. exp(2i * Num.pi / n * j)
  13. }
  14. }
  15. func polynomial_roots(f) {
  16. roots_of_unity(f.degree).map {|r| newton_inverse_method(f, r) }
  17. }
  18. var x = Poly(1)
  19. var f = (43*x**5 + 12*x**4 + -13*x**3 + 11*x**2 - 9*x - 4171)
  20. say "=> Polynomial:\n#{f} = 0"
  21. say "\n=> All roots (Newton's method):"
  22. polynomial_roots(f).each {|x| say "x = #{x}" }
  23. __END__
  24. => Polynomial:
  25. 43*x^5 + 12*x^4 - 13*x^3 + 11*x^2 - 9*x - 4171 = 0
  26. => All roots (Newton's method):
  27. x = 2.46080682285023567908265472618970060164526042431
  28. x = 0.729208457027589206734796460108780612566686172519 + 2.35669000613724060523419825983110598029981575934i
  29. x = -2.09914675217363727883426335808735184362187452421 + 1.43899056170716413073009457273260836659195140837i
  30. x = -2.09914675217363727883426335808735184362187452421 - 1.43899056170716413073009457273260836659195140837i
  31. x = 0.729208457027589206734796460108780612566686172519 - 2.35669000613724060523419825983110598029981575934i