Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine

Re: getting a cube root

by asarih (Hermit)
on Oct 08, 2003 at 19:25 UTC ( #297709=note: print w/replies, xml ) Need Help??

in reply to getting a cube root

All the replies posted so far finds a real root. Is there a method to find complex roots as well? Math::Complex doesn't seem to cut it.

Update: As pointed out below, c=r^(1/n)*e^(2*pi*i*j/n) (for j=0,1,...,n-1) will do the trick, but I was thinking someone should have written an easy access to the roots, as in:

@roots=complex_roots($real, $n)
to give all the n-th roots of $real. Hmmm.... This shouldn't be too difficult. I'll leave it as exercise to the reader. :)

Replies are listed 'Best First'.
Re: Re: getting a cube root
by snax (Hermit) on Oct 08, 2003 at 20:06 UTC
    You can use trig and brute force a method -- I'm a little busy to give it a go, but the complex roots lie on a circle in the complex plane of the same radius as the real root. With a cube root, that means you need to find the coords of the points at 120 and 240 degrees (1/3 and 2/3 around the circle) on that circle -- hopefully that's clear. For the nth root you need to look at the (i * 360/n) degree points with i = 0..(n-1). i=0 corresponds to the real root.


    #!/usr/bin/perl -w use strict; my $twoPi = 4 * atan2(1, 0); for (2..5) { my @roots = nthRoots(8, $_); print "$_ th roots of 8: $/"; foreach my $root (@roots) { print "$root->{Real} $root->{Imag}$/"; } }; sub nthRoots { my $x = shift; my $n = shift; # Should check for integer powers my @roots; $roots[0] = { Real => $x ** (1/$n), Imag => 0 }; for (1..($n-1)) { push @roots, { Real => $roots[0]->{Real} * cos( $_ * $twoPi/$n ), Imag => $roots[0]->{Real} * sin( $_ * $twoPi/$n ) }; }; return @roots; }

Log In?

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://297709]
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others contemplating the Monastery: (3)
As of 2022-08-08 09:43 GMT
Find Nodes?
    Voting Booth?

    No recent polls found