Beefy Boxes and Bandwidth Generously Provided by pair Networks
good chemistry is complicated,
and a little bit messy -LW

comment on

( #3333=superdoc: print w/replies, xml ) Need Help??
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

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

  • Are you posting in the right place? Check out Where do I post X? to know for sure.
  • Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
    <code> <a> <b> <big> <blockquote> <br /> <dd> <dl> <dt> <em> <font> <h1> <h2> <h3> <h4> <h5> <h6> <hr /> <i> <li> <nbsp> <ol> <p> <small> <strike> <strong> <sub> <sup> <table> <td> <th> <tr> <tt> <u> <ul>
  • Snippets of code should be wrapped in <code> tags not <pre> tags. In fact, <pre> tags should generally be avoided. If they must be used, extreme care should be taken to ensure that their contents do not have long lines (<70 chars), in order to prevent horizontal scrolling (and possible janitor intervention).
  • Want more info? How to link or How to display code and escape characters are good places to start.
Log In?

What's my password?
Create A New User
Domain Nodelet?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others cooling their heels in the Monastery: (5)
As of 2023-12-06 20:13 GMT
Find Nodes?
    Voting Booth?
    What's your preferred 'use VERSION' for new CPAN modules in 2023?

    Results (31 votes). Check out past polls.