in reply to Re: root function
in thread root function

Yes it does. (-3)**(1/3) results in nan; But so does the log approach, too.

The odd roots of negative numbers must be treated separately as they are limit cases.

I'd try something like:

if ($base>0) { return $base**(1/$root); } elsif ($base==0) { return 0; ## or do manage the special case 0**0; } elsif ($root)==int($root) && $root%2==1) { return -((-$base)**($root)); } else { return 'nan'; }

Not tested, so probably broken :)

Careful with that hash Eugene.

Replies are listed 'Best First'.
Re^3: root function
by swampyankee (Parson) on Jun 21, 2008 at 21:40 UTC

    The logarithms of negative numbers are defined; it's just that they require complex numbers to represent. It's not my fault that Perl (and C) can't cope with them ;-).

    All will become clear when one remembers that eπi = -1


    Information about American English usage here and here. Floating point issues? Please read this before posting. — emc

      ++

      But I said that would not work, not that it is wrong.

      BTW, my math teacher preferred to write eπi+1=0; she said that that form contains all the five really important numbers!

      Update: Well, she was a good teacher, now I realize she made that remark 31 years ago... and I still remember it

      Careful with that hash Eugene.

      Not complex numbers, series of complex numbers. e(2n+1)πi = -1, for any integer n. Which makes them undefined, for at least some purposes.

        Following your interpretation of "undefined", sqrt(2) should be undefined too (two solution), or arctan(x) for any x in the interval [-1,1] (infinite periodic).

        Careful with that hash Eugene.