Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

I need to calculate the nth (specifically the 4th) root. How do I do this using perl??
Thanks.

Replies are listed 'Best First'.
Re: Calculating Nth root using perl.
by kvale (Monsignor) on May 09, 2006 at 18:01 UTC
Re: Calculating Nth root using perl.
by salva (Canon) on May 09, 2006 at 18:19 UTC
    for the 4th root you can also use:
    my $r4 = sqrt sqrt $num;
      ++

      Reminds me of the joke about the carpenter who threw half the nails out, because they were facing the wrong way!

      -QM
      --
      Quantum Mechanics: The dreams stuff is made of

Re: Calculating Nth root using perl.
by Fletch (Bishop) on May 09, 2006 at 18:04 UTC

    Depending on the precision you need, log and exp may be all you need. If you need larger numbers you may need to call in Math::BigFloat or the like.

Re: Calculating Nth root using perl.
by swampyankee (Parson) on May 09, 2006 at 18:02 UTC

    Other than the snarky RTFM (Perl has an intrinsic exponentiation operator)

    $x = $y ** (1/4) if $y > 0;
    This is the revised code, in response to salva's and ikegami's comments
    if($y >= 0){ $x = $y ** (1/4); }else{ undef($x); die "Even roots of negative numbers require complex arithmetic\n"; }

    While the 4th root of a negative number exists, I'm presuming you don't need to do complex arithmetic. If you do, you man want to check out Math::Complex, although it appears to be developmental.

    emc

    "Being forced to write comments actually improves code, because it is easier to fix a crock than to explain it. "
    —G. Steele
      your code is not going to generate any error when $y < 0. That's usually a very bad thing!

      Just

      $x = $y ** (1/4);
      is better!
        I agree (++). Error handling shouldn't be removed without being replaced. Either handle it (by throwing an exception, displaying a warning, returning a complex number, returning an error code, etc) or let Perl handle it (by dying).