Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister
 
PerlMonks  

Re: How to get better exponentiation?

by syphilis (Archbishop)
on Jan 22, 2022 at 13:43 UTC ( [id://11140710]=note: print w/replies, xml ) Need Help??


in reply to How to get better exponentiation?

I came up with the following, which works for my use-case ...

Note that the floating point value 1/3 is not the same as the rational value 1/3, and while your subroutine works as you want for your use case, it won't work correctly for (eg) cube_root( -91197 ** 3 ), where it will return -91196.9999999999.
For general purposes, you therefore really need an implementation that performs cbrt(x), as opposed to pow(x, 1 / 3).
haukex has already shown that the excellent Math::Prime::Util::GMP module provides what you're after.
My own Math::MPFR module provides the same capability (courtesy of the mpfr C library):
C:\>perl -MMath::MPFR=":mpfr" -le "$op = Math::MPFR->new(-9117 ** 3); +Rmpfr_cbrt($op, $op, MPFR_RNDN); print $op;" -9.117e3
or, the more general:
C:\>perl -MMath::MPFR=":mpfr" -le "$op = Math::MPFR->new(-9117 ** 3); +Rmpfr_rootn_ui($op, $op, 3, MPFR_RNDN); print $op;" -9.117e3

Cheers,
Rob

Replies are listed 'Best First'.
Re^2: How to get better exponentiation?
by LanX (Saint) on Jan 22, 2022 at 14:54 UTC
    > Note that the floating point value 1/3 is not the same as the rational value 1/3,

    Good point, that might explain why it's considered undefined behavior by many.

    And an approximation algorithm designed to work with floating point exponents won't be able to handle anything like 1/$odd differently.

    Cheers Rolf
    (addicted to the Perl Programming Language :)
    Wikisyntax for the Monastery

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others musing on the Monastery: (4)
As of 2024-04-18 04:24 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found