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
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.