in reply to solve cubic equations
#!/usr/bin/env perl6 sub cubic(\a,\b,\c,\d) { my \Δ0 = b² - 3 × a × c; # note: special case when Δ0 == 0 my \Δ1 = 2 * b³ - 9 × a × b × c + 27 × a² × d; my \C = ( ( Δ1 + sqrt( Δ1² - 4 × Δ0³ + 0i) ) / 2 ).roots(3)[0]; my \ς = 1.roots(3); # cubic roots of unity return [0,1,2].map: -> \k { ( -1 / ( 3 × a ) ) × ( b + ς[k] × C + Δ0 / ( C × ς[k] ) ) } } my @vals = cubic(1,10,10,-10); # test use Test; plan 3; my $f = -> \x { x³ + 10 * x² + 10 * x - 10 }; is-approx $f( @vals[0] ), 0, 'first value'; is-approx $f( @vals[1] ), 0, 'second value'; is-approx $f( @vals[2] ), 0, 'third value';I had a hard time doing this with a code block on perlmonks, so I made a gist instead.
|
---|
Replies are listed 'Best First'. | |
---|---|
Re^2: solve cubic equations
by no_slogan (Deacon) on May 05, 2017 at 20:56 UTC | |
by bduggan (Pilgrim) on May 11, 2017 at 00:08 UTC | |
by no_slogan (Deacon) on May 11, 2017 at 02:02 UTC |