File tree 2 files changed +41
-0
lines changed
2 files changed +41
-0
lines changed Original file line number Diff line number Diff line change
1
+ #!/usr/bin/ruby
2
+
3
+ # Find all the roots `x` to a given polynomial `f`, such that f(x) = 0, using Newton's method.
4
+
5
+ func newton_inverse_method ( f , x = 1 f ) {
6
+ var df = derivative ( f )
7
+ while ( f ( x ) <~> 0 ) {
8
+ x = ( x - ( f ( x ) / df ( x ) ) )
9
+ }
10
+ return x
11
+ }
12
+
13
+ func roots_of_unity ( n ) {
14
+ n . of { |j |
15
+ exp ( 2 i * Num . pi / n * j )
16
+ }
17
+ }
18
+
19
+ func polynomial_roots ( f ) {
20
+ roots_of_unity ( f . degree ) . map { |r | newton_inverse_method ( f , r ) }
21
+ }
22
+
23
+ var x = Poly ( 1 )
24
+ var f = ( 43 *x **5 + 12 *x **4 + -13 *x **3 + 11 *x **2 - 9 *x - 4171 )
25
+
26
+ say "=> Polynomial:\n #{ f } = 0"
27
+
28
+ say "\n => All roots (Newton's method):"
29
+ polynomial_roots ( f ) . each { |x | say "x = #{ x } " }
30
+
31
+ __END__
32
+ => Polynomial:
33
+ 43*x^5 + 12*x^4 - 13*x^3 + 11*x^2 - 9*x - 4171 = 0
34
+
35
+ => All roots (Newton's method):
36
+ x = 2.46080682285023567908265472618970060164526042431
37
+ x = 0.729208457027589206734796460108780612566686172519 + 2.35669000613724060523419825983110598029981575934i
38
+ x = -2.09914675217363727883426335808735184362187452421 + 1.43899056170716413073009457273260836659195140837i
39
+ x = -2.09914675217363727883426335808735184362187452421 - 1.43899056170716413073009457273260836659195140837i
40
+ x = 0.729208457027589206734796460108780612566686172519 - 2.35669000613724060523419825983110598029981575934i
Original file line number Diff line number Diff line change @@ -530,6 +530,7 @@ A nice collection of day-to-day Sidef scripts.
530
530
* [ Polygonal representations] ( ./Math/polygonal_representations.sf )
531
531
* [ Polynomial interpolation] ( ./Math/polynomial_interpolation.sf )
532
532
* [ Polynomial regression] ( ./Math/polynomial_regression.sf )
533
+ * [ Polynomial roots] ( ./Math/polynomial_roots.sf )
533
534
* [ Pomerance condition for bpsw counter-example] ( ./Math/pomerance_condition_for_bpsw_counter-example.sf )
534
535
* [ Power divisors] ( ./Math/power_divisors.sf )
535
536
* [ Power integers] ( ./Math/power_integers.sf )
You can’t perform that action at this time.
0 commit comments