Skip to content

Instantly share code, notes, and snippets.

@bduggan
Created May 5, 2017 19:19
Show Gist options
  • Save bduggan/aa242e775adc805a2cb13f8341897547 to your computer and use it in GitHub Desktop.
Save bduggan/aa242e775adc805a2cb13f8341897547 to your computer and use it in GitHub Desktop.
#!/usr/bin/env perl6
sub cubic(\a,\b,\c,\d) {
my \Δ0 =- 3 × a × c;
my \Δ1 = 2 *- 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] ) )
}
}
# note: special case when Δ0 == 0
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';
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment