Skip to content

Commit f07c373

Browse files
committed
new file: Math/polynomial_roots.sf
1 parent 62923d3 commit f07c373

File tree

2 files changed

+41
-0
lines changed

2 files changed

+41
-0
lines changed

Math/polynomial_roots.sf

+40
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
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 = 1f) {
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(2i * 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

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -530,6 +530,7 @@ A nice collection of day-to-day Sidef scripts.
530530
* [Polygonal representations](./Math/polygonal_representations.sf)
531531
* [Polynomial interpolation](./Math/polynomial_interpolation.sf)
532532
* [Polynomial regression](./Math/polynomial_regression.sf)
533+
* [Polynomial roots](./Math/polynomial_roots.sf)
533534
* [Pomerance condition for bpsw counter-example](./Math/pomerance_condition_for_bpsw_counter-example.sf)
534535
* [Power divisors](./Math/power_divisors.sf)
535536
* [Power integers](./Math/power_integers.sf)

0 commit comments

Comments
 (0)