-
Notifications
You must be signed in to change notification settings - Fork 0
/
solve_cubic_equation.sf
58 lines (42 loc) · 1.86 KB
/
solve_cubic_equation.sf
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
#!/usr/bin/ruby
# Find all the solutions to a cubic equation.
# See also:
# https://en.wikipedia.org/wiki/Cubic_equation#General_cubic_formula
func solve_cubic_equation(a,b,c,d) {
var D0 = (b*b - 3*a*c)
var D1 = (2*b**3 - 9*a*b*c + 27*a*a*d)
var roots = []
var z = (-1 + sqrt(-3))/2
var C = cbrt((D1 - (sgn(D0)||-1)*sqrt(D1*D1 - 4*D0**3))/2)
0..2 -> each {|k|
var t = (C * z**k)
var x = -((b + t + D0/t))/(3*a)
roots << x
}
return roots.sort.flip
}
say ":: Solutions to: x^3 + 5*x^2 + 2*x - 8 = 0"
solve_cubic_equation(1, 5, 2, -8).each{.say}
say "\n:: Solutions to: x^3 + 4*x^2 + 7*x + 6 = 0"
solve_cubic_equation(1, 4, 7, 6).each{.say}
say "\n:: Solutions to: -36*x^3 + 8*x^2 - 82*x + 2850986 = 0:"
solve_cubic_equation(-36, 8, -82, 2850986).each{.say}
say "\n:: Solutions to: 15*x^3 - 22*x^2 + 8*x - 7520940423059310542039581 = 0:"
solve_cubic_equation(15, -22, 8, -7520940423059310542039581).each{.say}
__END__
:: Solutions to: x^3 + 5*x^2 + 2*x - 8 = 0
1
-2
-4+2.12412254817660303603850719702361574078813940692e-58i
:: Solutions to: x^3 + 4*x^2 + 7*x + 6 = 0
-1+1.41421356237309504880168872420969807856967187538i
-1-1.41421356237309504880168872420969807856967187538i
-2
:: Solutions to: -36*x^3 + 8*x^2 - 82*x + 2850986 = 0:
43
-21.3888888888888888888888888888888888888888888889-37.2053444322316098931489931056362914296357714346i
-21.3888888888888888888888888888888888888888888889+37.2053444322316098931489931056362914296357714346i
:: Solutions to: 15*x^3 - 22*x^2 + 8*x - 7520940423059310542039581 = 0:
79443853+7.88093052224943999146836047476866957980682147598e-51i
-39721925.7666666666666666666666666666666666666667-68800394.4491263888002422566466396186371117612128i
-39721925.7666666666666666666666666666666666666667+68800394.4491263888002422566466396186371117612128i