Syntactic Confectionery Delight PerlMonks

### Re: solve cubic equations

by bduggan (Pilgrim)
 on May 05, 2017 at 19:30 UTC ( #1189602=note: print w/replies, xml ) Need Help??

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.
#!/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
my \C = ( ( Δ1 + sqrt( Δ1² - 4 × Δ0³ + 0i) ) / 2 ).roots(3)[0];

Mathematically, your code is equivalent. (The arctan and cos are hidden inside roots.) Numerically, yours is potentially unstable. The first + in the line above might lose accuracy due to subtracting nearly-equal numbers. See Numerical Recipes, chapter 5.6. Unfortunately, sometimes we have to choose between code that looks nice and code that works.

The trouble with Perl 6 is that it's full of people who think it's a good idea to have a class called "Cool" which contains a hodgepodge of numerical and string-manipulation methods.

1. Yes, it's totally possible to optimize for accuracy, and yes, some situations call for that.
2. Allomorphic typing is cool.
1. Lots of things are cool, but you can't name them all "Cool" in your language.
2. This post is the 9th hit on google for the phrase "allomorphic typing." Of the ones above it, 7 are about linguistics, and the other one says that term was briefly in use in computer science 26 years ago. You don't frighten me with your silly language behavior.

Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1189602]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others scrutinizing the Monastery: (6)
As of 2023-09-22 11:05 GMT
Sections?
Information?
Find Nodes?
Leftovers?
Voting Booth?

No recent polls found

Notices?