in reply to root function

FunkyMonk has one way; another is

x(1/y) = eln(x)/y. Just beware that 00 should be undefined, and Perl's ** operator is essentially a wrapper around C's "pow" function, so it will almost certainly puke on (-3)(1/3), even though it shouldn't.


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

Replies are listed 'Best First'.
Re^2: root function
by psini (Deacon) on Jun 21, 2008 at 21:33 UTC

    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.

      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.
Re^2: root function
by ikegami (Patriarch) on Jun 21, 2008 at 21:37 UTC
    linux:
    $ perl -le'print -3 ** (1/3)' -1.44224957030741
    ActivePerl:
    >perl -le"print -3 ** (1/3)" -1.44224957030741

    Update: Oops, precedence problem

    $ perl -le'print( (-3) ** (1/3) )' nan
    >perl -e"print( (-3) ** (1/3) )" -1.#IND
      sini@ordinalfabetix:~$ perl -le"print ((-3)**(1/3));" nan sini@ordinalfabetix:~$

      Exponent operator ** has higher priority than unary minus so you are doing -(3**(1/3)) instead of ((-3)**(1/3)).

      This gives you accidentally the right result but it would tell you that square root of -2 == -1.414265...

      Careful with that hash Eugene.

        Too slow!

        This gives you accidentally the right result but it would tell you that square root of -2 == -1.414265...

        But -1.414265... is a square root of 2. :)

        Update: Ack! ignore this post.