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.
#!/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.

In reply to Re: solve cubic equations by bduggan
in thread solve cubic equations by no_slogan

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.