in reply to solve cubic equations
I prefer the solution involving radicals.
What's cool is that you can use square roots to solve quadratics, third roots to solve cubics, fourth roots to solve quartics, but you can't use just radicals from 5 and up.
Perl 6's built-in roots function comes in handy.
This equation comes right from the wikipedia entry, and uses the names of the variables there.
What's cool is that you can use square roots to solve quadratics, third roots to solve cubics, fourth roots to solve quartics, but you can't use just radicals from 5 and up.
Perl 6's built-in roots function comes in handy.
This equation comes right from the wikipedia entry, and uses the names of the variables there.
#!/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 |
In Section
Cool Uses for Perl