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

comment on

( [id://3333]=superdoc: print w/replies, xml ) Need Help??

There are times when Perl’s inbuilt exponentiation operator, **, just doesn’t cut it:

16:46 >perl -wE "my $cube_root = (-8)**(1/3); say $cube_root;" NaN 16:46 >perl -v This is perl 5, version 32, subversion 1 (v5.32.1) built for MSWin32-x +64-multi-thread

I note in the documentation that ** “...is implemented using C's pow(3) function...”, and that’s where the limitation appears to lie. (I’m using Strawberry Perl running under Windows 8.1 64-bit. I get the same results using Raku. I don’t know if C’s pow(3) function has the same limitations under Unix?)

I came up with the following, which works for my use-case but is really a kludge:

sub cube_root { my ($n) = @_; return (abs( $n ) ** (1 / 3)) * ($n < 0 ? -1 : 1); }

So, what’s the quickest/simplest/correct way to get Perl to act like the calculator app that comes with Windows, and give -2 as the cube root of -8? (I’m only interested in the real solution.) I had a quick look through CPAN, but nothing stood out. I’m probably overlooking the obvious.

Thanks,

Athanasius <°(((><contra mundum Iustus alius egestas vitae, eros Piratica,


In reply to How to get better exponentiation? by Athanasius

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post; it's "PerlMonks-approved HTML":



  • Are you posting in the right place? Check out Where do I post X? to know for sure.
  • Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
    <code> <a> <b> <big> <blockquote> <br /> <dd> <dl> <dt> <em> <font> <h1> <h2> <h3> <h4> <h5> <h6> <hr /> <i> <li> <nbsp> <ol> <p> <small> <strike> <strong> <sub> <sup> <table> <td> <th> <tr> <tt> <u> <ul>
  • Snippets of code should be wrapped in <code> tags not <pre> tags. In fact, <pre> tags should generally be avoided. If they must be used, extreme care should be taken to ensure that their contents do not have long lines (<70 chars), in order to prevent horizontal scrolling (and possible janitor intervention).
  • Want more info? How to link or How to display code and escape characters are good places to start.
Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others meditating upon the Monastery: (4)
As of 2024-04-19 21:05 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found