MPFR(3pm)
okay bestie, welcome to MPFR(3pm) โ the User Contributed Perl Documentation page for Math::MPFR. Let's get into it ๐
โจ NAME โจ
Math::MPFRโ perl interface to the MPFR (floating point) library. periodt.
๐ DEPENDENCIES ๐
Bestie, this module needs the MPFR and GMP C libraries. Install the GMP library first, because it's a pre-requisite for MPFR. No cap.
- The GMP library is available from
https://gmplib.org. - The MPFR library is available from
https://www.mpfr.org.
Documentation for current mpfr functions can be found at: www.mpfr.org/mpfr-current/mpfr.html#Function-and-Type-Index .
๐ฆ DESCRIPTION ๐ฆ
A bigfloat module utilising the MPFR library. The main aim of this module is to wrap the floating point functions provided by that library. We also access many of those functions via operator overloading. (A small number of customised functions, not found in the MPFR library, are also available.)
โจ SYNOPSIS โจ
This synopsis is very brief. My attempts at providing a reasonable coverage in this section always result in something that is ridiculously complex :-( (felt that)
# This synopsis is very brief. My attempts at providing a
# reasonable coverage in this section always result in
# something that is ridiculously complex :-(
use Math::MPFR qw(:mpfr);
# Create a Math::MPFR object with an assigned value. The
# returned object will have current default precision, and
# the value will be rounded according to current dwfault
# rounding mode. In this example, we provide a string as the
# argument, but non-string arguments are also permitted.
my $rop = Math::MPFR->new('1.2e-10');
# Other ways of assigning a string using new() to create an
# equivalent Math::MPFR object include:
# my $rop = Math::MPFR->new('1.2@-10');
# my $rop = Math::MPFR->new("1.2\@-10");
# Octal (base 8):
# my $rop = Math::MPFR->new('1.0176077644330267e-11', 8);
# my $rop = Math::MPFR->new('0x1.07e1fe91b0b7p-33');
# Specify base (16) if '0x' prefix is not provided:
# my $rop = Math::MPFR->new('1.07e1fe91b0b7p-33', 16);
# Display the value held by $rop.
print $rop; # 1.2e-10
# Other ways of printing out the value include:
# print mpfrtoa($rop); # 1.2e-10
# Rmpfr_printf("%Rg", $rop); # 1.2e-10
That's the vibe. Slay.
๐ซ ROUNDING MODE ๐ซ
As of mpfr-3.0.0, the rounding values are:
MPFR_RNDN(numeric value =0) โ Round to nearest.MPFR_RNDZ(numeric value =1) โ Round towards zero.MPFR_RNDU(numeric value =2) โ Round towards+infinity.MPFR_RNDD(numeric value =3) โ Round towards-infinity.
Previously they were named (respectively) GMP_RNDN, GMP_RNDZ, GMP_RNDU and GMP_RNDD.
You can use either the "GMP_*" or the "MPFR_*" renditions, but the former is discouraged. iykyk.
Also available are:
mpfr-3.0.0and later:MPFR_RNDA(numeric value =4) โ Round away from zero.
mpfr-4.0.0and later:MPFR_RNDF(numeric value =5) โ Faithful rounding.
These last two rounding modes will cause a fatal error if the mpfr library against which Math::MPFR has been built is not sufficiently recent.
MPFR_RNDFis experimental โ the computed value is either that corresponding toMPFR_RNDDor that corresponding toMPFR_RNDU. In particular when those values are identical, i.e., when the result of the corresponding operation is exactly representable, that exact result is returned. Thus, the computed result can take at most two possible values, and in absence of underflow/overflow, the corresponding error is strictly less than one ulp (unit in the last place) of that result and of the exact result. ForMPFR_RNDF, the returned value and the inexact flag are unspecified, the divide-by-zero flag is as with other roundings, and the underflow and overflow flags match what would be obtained in the case the computed value is the same as withMPFR_RNDDorMPFR_RNDU. The results may not be reproducible, and it may not work with all functions. Please report bugs.
MPFR_RNDN (the 'round to nearest' mode) works as in the IEEE P754 standard: in case the number to be rounded lies exactly in the middle of two representable numbers, it is rounded to the one with the least significant bit set to zero. For example, the number 5, which is represented by '101' in binary, is rounded to '10p1' (4) with a precision of two bits, and not to '11p1' (6). This rule avoids the "drift" phenomenon mentioned by Knuth in volume 2 of The Art of Computer Programming (section 4.2.2, pages 221-222).
Most Math::MPFR functions take as first argument the destination variable, as second and following arguments the input variables, as last argument a rounding mode, and have a return value of type 'int'. If this value is zero, it usually means that the value stored in the destination variable is the exact result of the corresponding mathematical function. If the returned value is positive (resp. negative), it usually means the value stored in the destination variable is greater (resp. lower) than the exact result. For example with the 'GMP_RNDU' rounding mode, the returned value is usually positive, except when the result is exact, in which case it is zero. In the case of an infinite result, it is considered as inexact when it was obtained by overflow, and exact otherwise. A NaN result (Not-a-Number) always corresponds to an inexact return value.
See also the Rmpfr_round_nearest_away() function in the ROUNDING MODE FUNCTIONS section for the mode "round to nearest, ties away from zero".
๐ง MEMORY MANAGEMENT ๐ง
Objects are created with new() or with the Rmpfr_init* functions. All of these functions return an object that has been blessed into the package Math::MPFR. They will therefore be automatically cleaned up by the DESTROY() function whenever they go out of scope.
For each Rmpfr_init* function there is a corresponding function called Rmpfr_init*_nobless which returns an unblessed object. If you create Math::MPFR objects using the '_nobless' versions, it will then be up to you to clean up the memory associated with these objects by calling Rmpfr_clear($op) for each object, or Rmpfr_clears($obj1, $obj2, ....). Alternatively such objects will be cleaned up when the script ends. Because these objects created by the '_nobless' functions have not been blessed into the Math::MPFR package, the overloaded operators will not work with them.
๐ MIXING GMP OBJECTS WITH MPFR OBJECTS ๐
Some of the Math::MPFR functions below take as arguments one or more of the GMP types mpz (integer), mpq (rational) and mpf (floating point). (Such functions are marked as taking mpz/mpq/mpf arguments.)
For these functions to work you need to have loaded either:
Math::GMPfrom CPAN. (This module provides access tompzobjects only - NOTmpfandmpqobjects.)
AND/OR
Math::GMPz(formpztypes),Math::GMPq(formpqtypes) andMath::GMPf(formpftypes).
๐ฅ PASSING __float128 VALUES ๐ฅ
There are 3 ways to pass __float128 values to/from Math::MPFR. Option 1) is the preferred option:
- Build perl (
5.21.4or later) with-Dusequadmath; build thempfr-4.0.0(or later) library with the configure option--enable-float128. Then build Math::MPFR in the usual way. If the build process does not then result in a Math::MPFR module that supports the__float128NV try providing the"F128=1"arg to theMakefile.PL(which will define the symbolMPFR_WANT_FLOAT128):
perl Makefile.PL F128=1
(And please file a bug report, because the aim is that you should not need to specify F128=1 here.)
Then you can pass your perl's __float128 NV values directly to/from Math::MPFR using:
Rmpfr_set_float128() or Rmpfr_set_NV() and
Rmpfr_get_float128() or Rmpfr_get_NV()
This will also mean that overloaded operations that receive an NV will evaluate that (__float128) NV to its full precision. And assigning the NV as Math::MPFR->new($NV) will also work as intended.
NOTE:
- If you have built perl with
-Dusequadmath, but the mpfr library was not built withfloat128support , then bothRmpfr_set_NV()andRmpfr_get_NV()will still set/get__float128values. - Also, overloaded operations that receive an NV will still evaluate that (
__float128) NV to its full precision. - It's only
Rmpfr_set_float128()andRmpfr_get_float128()that will not be available.
- On a perl that was not built with
-Dusequadmath, installMath::Float128, build thempfr-4.0.0(or later) library with the configure option--enable-float128, and build Math::MPFR by providing the"F128=1"arg to theMakefile.pl:
perl Makefile.PL F128=1
Then you can pass the values of the Math::Float128 objects to and from Math::MPFR objects using:
Rmpfr_set_FLOAT128() and Rmpfr_get_FLOAT128()
- Convert the
__float128values to a string and pass them to and from Math::MPFR using:
Rmpfr_strtofr()/Rmpfr_set_str() and Rmpfr_get_str()
๐ PASSING _Decimal64 & _Decimal128 VALUES ๐
Install Math::Decimal64 and/or Math::Decimal128 and build the mpfr library (version 3.1.0 or later for _Decimal64, version 4.1.0 or later for _Decimal128) with the --enable-decimal-float option. The Math::MPFR build process should detect the _Decimal64/_Decimal128 availability and include or exclude the support accordingly.
If the auto-detection fails to detect the availability, you can override it by providing the "D64=1" and/or "D128=1" arg to the the Makefile.PL (either of which will define MPFR_WANT_DECIMAL_FLOATS):
perl Makefile.PL D64=1 D128=1
You can then pass _Decimal64/_Decimal128 values between Math::MPFR and Math::Decimal64/Math::Decimal128 using:
Rmpfr_set_DECIMAL64() and Rmpfr_get_DECIMAL64()
Rmpfr_set_DECIMAL128() and Rmpfr_get_DECIMAL128()
NOTE: It is allowable to pass any or all of "D64=1", "D128=1" and "F128=1" args to the Makefile.PL.
To force the removal of _Decimal64/Decimal128 support in Math::MPFR, simply provide "D64=0" and/or "D128=0" as arguments to the Makefile.PL:
perl Makefile.PL D64=0 D128=0
๐ FUNCTIONS ๐
The following functions are generally wrappers around an mpfr function of the same name. eg. Rmpfr_swap() is a wrapper around mpfr_swap().
"$rop", "$op1", "$op2", etc. are Math::MPFR objects.
$inexโ it's a signed integer value (IV) that lots of the mpfr functions hand back to you.$inex == 0means the function's result was exact โจ$inex < 0means the function's result got rounded to a value that is less than the exact result.$inex > 0means the function's result got rounded to a value that is greater than the exact result.
$uiโ any integer that fits into a Cunsigned long int, periodt.$siโ any integer that fits into a Csigned long int.$ujโ any integer that fits into a Cuintmax_t. Lowkey don't use any of these functions unless your perl's UV is at least as big as auintmax_t.$sjโ any integer that fits into a Cintmax_t. Don't use any of these functions unless your perl's IV is at least as big as anintmax_t.$doubleis a C double and$floatis a C float โฆ but both will be represented in Perl as an NV.$ldmeans a long double. Don't use these functions if the precision of your Perl's NV is less than the precision of along double.$f128means a__float128. Don't use these functions unless your Perl's NV is a__float128&& mpfr has been configured with--enable-float128. (Note that versions of mpfr prior to 4.0.0 cannot be configured with--enable-float128.)$boolโ a value (usually asigned long int) where the only thing we care about is whether it's false or true.$strโ just a string of symbols that represent a number, like1234567890987654321234567E7orzsa34760sdfgq123r5@11. Valid bases for MPFR numbers are 2 to 62.$rndโ one of the 5 rounding mode values (we discussed those above) that lots of functions need as their rounding arg. In my code, instead of passing a perl scalar, I usually just write the bareword form โMPFR_RNDNorMPFR_RNDUor โฆ etc.$pโ the (signed int) value for precision.
๐ ROUNDING MODE FUNCTIONS ๐
Rmpfr_set_default_rounding_mode($rnd);Sets the default rounding mode to$rnd(where$rndcan be one ofMPFR_RNDN,MPFR_RNDU,MPFR_RNDZ,MPFR_RNDDandMPFR_RNDA). Note thatMPFR_RNDAis available only if Math::MPFR has been built against mpfr-3.0.0 or later. The default rounding mode is to nearest initially (MPFR_RNDN). The default rounding mode is the rounding mode that is used in overloaded operations.$si = Rmpfr_get_default_rounding_mode();Returns to$sithe numeric value (0, 1, 2, 3 or 4) of the current default rounding mode. This will initially be 0.$inex = Rmpfr_prec_round($rop, $p, $rnd);Rounds$ropaccording to$rndwith precision$p, which may be different from that of$rop. If$pis greater or equal to the precision of$rop, then new space is allocated for the mantissa, and it is filled with zeroes. Otherwise, the mantissa is rounded to precision$pwith the given direction. In both cases, the precision of$ropis changed to$p. The precision$pcan be any integer betweenRMPFR_PREC_MINandRMPFR_PREC_MAX.$inex = Rmpfr_round_nearest_away(\&function, $rop, @input_args);This is a perl implementation (and not a wrapping) of thempfr_round_nearest_awaymacro introduced in mpfr-4.0.0. You can use this function so long as Math::MPFR has been built against mpfr-3.0.0 or later. This rounding is defined in the same way asMPFR_RNDN, except in case of tie, where the value away from zero is returned. The first arg is a reference to the perl subroutine you wish to call, and the remaining args are the args that the subroutine usually takes (minus the rounding arg). For example:
$inex = Rmpfr_round_nearest_away(\&Rmpfr_add, $rop,
$op1, $op2);
$inex = Rmpfr_round_nearest_away(\&Rmpfr_strtofr, $rop,
'1e-200', 10);
$inex = Rmpfr_round_nearest_away(\&Rmpfr_prec_round,
$rop, $prec);
The "function" being called must be one that returns the ternary int (-ve for "less than", 0 for "exact", and +ve for "greater than"). Unlike the more efficient rndna(), this function requires that Rmpfr_get_emin() is greater than Rmpfr_get_emin_min(). If you're not concerned about correct rounding (nearest away) of the value +/- 0.25 * (2 ** Rmpfr_get_emin()) then you can instead use the rndna function (immediately below).
$inex = rndna(\&function, $rop, @input_args);A more efficient version of the (above)Rmpfr_round_nearest_awayfunction. However, it will not correctly deal with the value+/- 0.25 * (2 ** Rmpfr_get_emin()). UnlikeRmpfr_round_nearest_away(), this function allows thatRmpfr_get_emin() == Rmpfr_get_emin_min().
๐ธ INITIALIZATION ๐ธ
- A variable should be initialized once only.
- First read the section 'MEMORY MANAGEMENT' (above).
Rmpfr_set_default_prec($p);Set the default precision to be exactly$pbits. The precision of a variable means the number of bits used to store its mantissa. All subsequent calls tompfr_initwill use this precision, but previously initialized variables are unaffected. This default precision is set to 53 bits initially. The precision can be any integer betweenRMPFR_PREC_MINandRMPFR_PREC_MAX.$ui = Rmpfr_get_default_prec();Returns the default MPFR precision in bits.$rop = Math::MPFR->new();$rop = Math::MPFR::new();$rop = new Math::MPFR();$rop = Rmpfr_init();$rop = Rmpfr_init_nobless();Initialize$rop, and set its value to NaN. The precision of$ropis the default precision, which can be changed by a call toRmpfr_set_default_prec. NOTE: Thenew()sub can accept an argument โ in which case$ropis initialized and the given value assigned to it. If the argument is a Math::GMP or Math::GMPz or Math::GMPq object then the returned Math::MPFR object's value is set in accordance with current default precision and current default rounding mode. If the argument is a PV then a second optional argument specifying the numeric base of the string is permitted. SeeCOMBINED INITIALIZATION AND ASSIGNMENTbelow for more details.$rop = Rmpfr_init2($p);$rop = Rmpfr_init2_nobless($p);Initialize$rop, set its precision to be exactly$pbits, and set its value to NaN. To change the precision of a variable which has already been initialized, useRmpfr_set_precinstead. The precision$pcan be any integer betweenRMPFR_PREC_MINandRMPFR_PREC_MAX.@rops = Rmpfr_inits($how_many);@rops = Rmpfr_inits_nobless($how_many);Returns an array of$how_manyMath::MPFR objects โ initialized, with a value of NaN, and with default precision. (These functions do not wrapmpfr_inits.)@rops = Rmpfr_inits2($p, $how_many);@rops = Rmpfr_inits2_nobless($p, $how_many);Returns an array of$how_manyMath::MPFR objects โ initialized, with a value of NaN, and with precision of$p. (These functions do not wrapmpfr_inits2.)Rmpfr_set_prec($op, $p);Reset the precision of$opto be exactly$pbits. The previous value stored in$opis lost. The precision$pcan be any integer betweenRMPFR_PREC_MINandRMPFR_PREC_MAX. If you want to keep the previous value stored in$op, useRmpfr_prec_roundinstead.$si = Rmpfr_get_prec($op);Return to$sithe precision actually used for assignments of$op, i.e. the number of bits used to store its mantissa.Rmpfr_set_prec_raw($rop, $p);Reset the precision of$ropto be exactly$pbits. The only difference withmpfr_set_precis that$pis assumed to be small enough so that the mantissa fits into the current allocated memory space for$rop. Otherwise an error will occur.$min_prec = Rmpfr_min_prec($op);(This function is implemented only when Math::MPFR is built against mpfr-3.0.0 or later. Thempfr_min_precfunction was not present in earlier versions of mpfr.)$min_precis set to the minimal number of bits required to store the significand of$op, and 0 for special values, including 0. (Warning: the returned value can be less thanRMPFR_PREC_MIN.)$minimum_precision = RMPFR_PREC_MIN;$maximum_precision = RMPFR_PREC_MAX;Returns the minimum/maximum precision for Math::MPFR objects allowed by the mpfr library being used.
๐ ASSIGNMENT ๐
okay so we were doing the Rmpfr_set_* lineup and bestie it is STILL going, this family has main-character energy and refuses to leave the stage ๐ซถ here's the rest of the roster:
$inex = Rmpfr_set($rop, $op, $rnd);
$inex = Rmpfr_set_ui($rop, $ui, $rnd);
$inex = Rmpfr_set_si($rop, $si, $rnd);
$inex = Rmpfr_set_sj($rop, $sj, $rnd);
$inex = Rmpfr_set_uj($rop, $uj, $rnd);
$inex = Rmpfr_set_IV($rop, $iv, $rnd); # $iv is $Config{ivtype}
$inex = Rmpfr_set_d ($rop, $double, $rnd);
$inex = Rmpfr_set_ld($rop, $ld, $rnd); # long double
$inex = Rmpfr_set_NV($rop, $nv, $rnd); # $nv is $Config{nvtype}
$inex = Rmpfr_set_LD($rop, $LD, $rnd); # $LD is a Math::LongDouble
# object
$inex = Rmpfr_set_z($rop, $z, $rnd); # $z is a mpz object.
$inex = Rmpfr_set_q($rop, $q, $rnd); # $q is a mpq object.
$inex = Rmpfr_set_f($rop, $f, $rnd); # $f is a mpf object.
$inex = Rmpfr_set_flt($rop, $nv, $rnd); # mpfr-3.0.0 and later only
# Set $rop to the value of
# $nv rounded to a float.
$inex = Rmpfr_set_float16($rop, $nv, $rnd); # mpfr-4.3.0 and later only
# & only on 64-bit systems.
$inex = Rmpfr_set_bfloat16($rop, $nv, $rnd); # mpfr-4.3.0 and later only
# & only on 64-bit systems.
$inex = Rmpfr_set_float128($rop, $f128, $rnd);# nvtype is __float128
# && mpfr-4.0.0 or later
# && mpfr lib built with
# --enable-float128.
$inex = Rmpfr_set_DECIMAL64($rop, $D64, $rnd);# mpfr-3.1.0 or later &&
# mpfr lib built with
# --enable-decimal-float
# $D64 is a
# Math::Decimal64 object
$inex = Rmpfr_set_DECIMAL128($rop, $D128, $rnd);# mpfr-3.1.0 or later &&
# mpfr lib built with
# --enable-decimal-float.
# $D128 is a
# Math::Decimal128 object
$inex = Rmpfr_set_FLT($rop, $FLT, $rnd); # Set $rop to the value of
# the Math::Float32 object $FLT.
$inex = Rmpfr_set_FLOAT16($rop, $F16, $rnd); # Set $rop to the value of the
# Math::Float16 object $F16
$inex = Rmpfr_set_BFLOAT16($rop, $BF16, $rnd);# Set $rop to the value of the
# Math::Bfloat16 object $BF16
$inex = Rmpfr_set_FLOAT128($rop, $F128, $rnd);# mpfr-4.0.0 and later
# && mpfr lib built with
# --enable-float128.
# $F128 is a
# Math::Float128 object.
So what's the vibe of all of these? โจ They set the value of $rop from the 2nd argument, rounded to the precision of $rop and towards whatever direction $rnd says. Important lil thing: even a long int might have to get rounded if the destination precision is narrower than the machine word width. iykyk.
The return value is the classic ternary situation ๐:
- zero when
$rop== 2nd arg - positive when
$rop> 2nd arg - negative when
$rop< 2nd arg
For mpfr_set_d, be careful bestie โ the input number $double might not even be exactly representable as a double-precision number (thinking of 0.1, the eternal menace ๐). In that case the C compiler rounds it to a double-precision number first, and only then does it become a mpfr floating-point number.
Rmpfr_set_float16 and Rmpfr_set_bfloat are currently unavailable to 32-bit systems. Where they are enabled, these 2 functions set $rop to the value of the given NV argument, rounded (according to $rnd) to a _Float16 or (respectively) a __bf16.
NOTE: ๐ฅ 1.Rmpfr_set_IVrequires that$ivhas it's IOK flag set, andRmpfr_set_NVrequires that$nvhas its NOK flag set. Otherwise these functions will croak. Best to first checkIOK_flag($iv)orNOK_flag($nv), both of which will return a non-zero value if and only if the flag in question is set. 2.Rmpfr_set_IValso handles unsigned (UV) arguments. ๐
Now the <rainbow>two-to-the-power-of</rainbow> girlies arrived:
$inex = Rmpfr_set_ui_2exp($rop, $ui, $exp, $rnd);
$inex = Rmpfr_set_si_2exp($rop, $si, $exp, $rnd);
$inex = Rmpfr_set_uj_2exp($rop, $uj, $exp, $rnd);
$inex = Rmpfr_set_sj_2exp($rop, $sj, $exp, $rnd);
$inex = Rmpfr_set_z_2exp($rop, $z, $exp, $rnd); # mpfr-3.0.0 & later only
These set the value of $rop from the 2nd arg multiplied by two to the power $exp, rounded towards the given direction $rnd. ๐ธ Note that the input 0 gets converted to +0. (And psst โ $z is a GMP mpz object.)
strings-to-numbers, the set_str era ๐
$iv = Rmpfr_set_str($rop, $str, $base, $rnd);
Set $rop to the value of $str in base $base โ that's (0,2..36), or if Math::MPFR has been built against mpfr-3.0.0 or later, (0,2..62) โ rounded in direction $rnd to the precision of $rop. The exponent is read in decimal. ๐ฆ
This function returns 0 if the entire string is a valid number in base $base. Otherwise it returns -1.
If -1 comes back:
- the non-numeric flag (which was initialised to
0) will be incremented. You can query/clear/reset the value of the flag with (resp.)nnumflag()/clear_nnum()/set_nnum()โ all of which are documented below (in "MISCELLANEOUS"); - a warning will be emitted if
$Math::MPFR::NNWis set to1(default is0).
If $base is zero, the base is set according to these rules:
- if the string starts with
'0b'or'0B'the base is set to2; - if the string starts with
'0x'or'0X'the base is set to16; - otherwise the base is set to
10.
These exponent symbols can be used:
'@'โ can be used for any base;'e'or'E'โ can be used only with bases <= 10;'p'or'P'โ can be used to introduce binary exponents with hexadecimal or binary strings.
See the MPFR library documentation for more details. See also 'Rmpfr_inp_str' (below).
Now, a perl-specific trap that WILL humble you ๐ โ because of the special significance of the '@' symbol in perl, make sure you assign to strings using single quotes, not double quotes, when using '@' as the exponent marker. If you must use double quotes (which is hard to believe) then you need to escape the '@'. ie the following two assignments are equivalent:
Rmpfr_set_str($rop, '.1234@-5', 10, GMP_RNDN);
Rmpfr_set_str($rop, ".1234\@-5", 10, GMP_RNDN);
But the following assignment won't do what you want:
Rmpfr_set_str($rop, ".1234@-5", 10, GMP_RNDN);
strtofr, the exactness girlie โจ
$inex = Rmpfr_strtofr($rop, $str, $base, $rnd);
This function differs from Rmpfr_set_str() mainly in that it returns the usual "exactness" ternary value ($inex). ๐
Read a floating point number from a string $str in base $base, rounded in the direction $rnd. If successful, the result is stored in $rop. If $str doesn't start with a valid number then $rop is set to zero.
Parsing follows the standard C strtod function with some extensions. Case is ignored. After optional leading whitespace, one has a subject sequence consisting of an optional sign ('+' or '-'), and either numeric data or special data. The subject sequence is defined as the longest initial subsequence of the input string, starting with the first non-whitespace character, that is of the expected form.
The form of numeric data is a non-empty sequence of significand digits with an optional decimal point, and an optional exponent consisting of an exponent prefix followed by an optional sign and a non-empty sequence of decimal digits. A significand digit is either a decimal digit or a Latin letter (62 possible characters), with 'a' = 10, 'b' = 11, ..., 'z' = 36; its value must be strictly less than the base. The decimal point can be either the one defined by the current locale or the period (the first one is accepted for consistency with the C standard and the practice, the second one is accepted to allow the programmer to provide MPFR numbers from strings in a way that does not depend on the current locale). The exponent prefix can be 'e' or 'E' for bases up to 10, or '@' in any base; it indicates a multiplication by a power of the base. In bases 2 and 16, the exponent prefix can also be 'p' or 'P', in which case it introduces a binary exponent: it indicates a multiplication by a power of 2 (there is a difference only for base 16). The value of an exponent is always written in base 10. In base 2, the significand can start with '0b' or '0B', and in base 16, it can start with '0x' or '0X'.
If the argument $base is 0, then the base is automatically detected as follows. If the significand starts with '0b' or '0B', base 2 is assumed. If the significand starts with '0x' or '0X', base 16 is assumed. Otherwise base 10 is assumed. Other allowable values for $base are 2 to 62.
Note ๐ธ: The exponent must contain at least a digit. Otherwise the possible exponent prefix and sign are not part of the number (which ends with the significand). Similarly, if'0b','0B','0x'or'0X'is not followed by a binary/hexadecimal digit, then the subject sequence stops at the character'0'.
Special data (for infinities and NaN) can be '@inf@' or '@nan@(n-char-sequence)', and if BASE <= 16, it can also be 'infinity', 'inf', 'nan' or 'nan(n-char-sequence)', all case insensitive. A 'n-char-sequence' is a non-empty string containing only digits, Latin letters and the underscore (0, 1, 2, ..., 9, a, b, ..., z, A, B, ..., Z, _). Note: one has an optional sign for all data, even NaN. ๐
inf, nan and zero โ the special girlies ๐ง
Rmpfr_set_inf($rop, $si);
Rmpfr_set_nan($rop);
Rmpfr_set_zero($rop, $si); # mpfr-3.0.0 and later only.
Set the variable $rop to infinity or NaN (Not-a-Number) or zero respectively. In 'Rmpfr_set_inf' and 'Rmpfr_set_zero', the sign of $rop is positive if 2nd arg >= 0. Else the sign is negative. ๐
swap โ trading places ๐ฆ
Rmpfr_swap($op1, $op2);
Swap the values $op1 and $op2 efficiently. Warning: the precisions are exchanged too; in case the precisions are different, 'mpfr_swap' is thus not equivalent to three 'mpfr_set' calls using a third auxiliary variable. ๐
################################################
๐ COMBINED INITIALIZATION AND ASSIGNMENT ๐
๐จ ok so FIRST THING: do NOT use these functions if$rophas already been initialised. bestie. pls. use theRmpfr_set*functions over in the ASSIGNMENT section (above) instead. ๐
Also โ go read the MEMORY MANAGEMENT section (above) before you touch any of this. that's the homework. do it. ๐
$rop = Math::MPFR->new($arg);
$rop = Math::MPFR::new($arg);
$rop = new Math::MPFR($arg);
Returns a Math::MPFR object holding the value of $arg, rounded in the default rounding direction, with default precision. $arg can be any of these:
- a number (signed integer, unsigned integer, signed fraction or unsigned fraction) ๐
- a string that represents a numeric value
- an object (of type Math::GMPf, Math::GMPq, Math::GMPz, orMath::GMP)
If $arg is a string, you can hand new() an optional extra argument that says what base the number is in. Legal values for that base are 0 and 2 to 62. If $arg is a string and you don't pass that extra argument, the base gets deduced for you. โจ
See 'Rmpfr_set_str' above for the whole explanation of how that deduction happens, plus the rules about the string format.
NOTE: if$argis both an NV (floating point value) and a PV (string), then the value specified by the PV (the string) is the one that gets used. which is probably what you want (less likely so on perl-5.18.4 and earlier ๐). But for real though โ there's no guaranteed way for thenew()function to correctly tell, so it's genuinely best to just avoid passing values like that. either that, or explicitly use the value you want by doing anRmpfr_init()followed by the appropriate'Rmpfr_set_*'function documented in the previous section. Or, if such a thing exists, you could call the appropriate'Rmpfr_init_set_*'function documented immediately below instead. ๐
Note that these functions (below) return a list of 2 values. two!! count them. ๐
($rop, $inex) = Rmpfr_init_set ($op, $rnd);
($rop, $inex) = Rmpfr_init_set_nobless($op, $rnd);
($rop, $inex) = Rmpfr_init_set_ui ($ui, $rnd);
($rop, $inex) = Rmpfr_init_set_ui_nobless($ui, $rnd);
($rop, $inex) = Rmpfr_init_set_si ($si, $rnd);
($rop, $inex) = Rmpfr_init_set_si_nobless($si, $rnd);
($rop, $inex) = Rmpfr_init_set_d ($double, $rnd);
($rop, $inex) = Rmpfr_init_set_d_nobless($double, $rnd);
($rop, $inex) = Rmpfr_init_set_ld ($ld, $rnd);
($rop, $inex) = Rmpfr_init_set_ld_nobless($ld, $rnd);
($rop, $inex) = Rmpfr_init_set_float128 ($f128, $rnd);
($rop, $inex) = Rmpfr_init_set_float128_nobless($f128, $rnd);
($rop, $inex) = Rmpfr_init_set_f ($f, $rnd);# $f is a mpf object
($rop, $inex) = Rmpfr_init_set_f_nobless($f, $rnd);# $f is a mpf object
($rop, $inex) = Rmpfr_init_set_z ($z, $rnd);# $z is a mpz object
($rop, $inex) = Rmpfr_init_set_z_nobless($z, $rnd);# $z is a mpz object
($rop, $inex) = Rmpfr_init_set_q ($q, $rnd);# $q is a mpq object
($rop, $inex) = Rmpfr_init_set_q_nobless($q, $rnd);# $q is a mpq object
($rop, $inex) = Rmpfr_init_set_IV ($IV,$rnd);# $IV is $Config{ivtype}
($rop, $inex) = Rmpfr_init_set_IV_nobless($IV,$rnd);# $IV is $Config{ivtype}
($rop, $inex) = Rmpfr_init_set_NV ($NV,$rnd);# $NV is $Config{nvtype}
($rop, $inex) = Rmpfr_init_set_NV_nobless($NV,$rnd);# $NV is $Config{nvtype}
These initialise $rop and set its value from the 1st arg, rounded to direction $rnd. The precision of $rop gets taken from the active default precision, as set by 'Rmpfr_set_default_prec'. ๐ธ
($rop, $si) = Rmpfr_init_set_str($str, $base, $rnd);
($rop, $si) = Rmpfr_init_set_str_nobless($str, $base, $rnd);
Initialize $rop and set its value from $str in base $base, rounded to direction $rnd. If $str was a valid number, then $si will be set to 0. Else it gets set to -1. and if $si is -1, two things happen, ok:
- the non-numeric flag (which was initialised to
0) will be incremented. You can query / clear / reset the value of that flag with (respectively)nnumflag()/clear_nnum()/set_nnum()โ all of which are documented below (in "MISCELLANEOUS"). ๐ง - A warning will be emitted if
$Math::MPFR::NNWis set to1(default is0). โ ๏ธ
See 'Rmpfr_set_str' (above) and 'Rmpfr_inp_str' (below).
๐ซ CONVERSION ๐ซ
Rmpfr_get_str
$str = Rmpfr_get_str($op, $base, $digits, $rnd);
Returns a string of the form, eg, '8.3456712@2' โ which means '834.56712'. The "mantissa" portion of the returned string gets presented in base $base. The "exponent" portion is in base 10. $digits specifies the number of digits you want output in the mantissa. (Trailing zeroes are removed, as a treat. ๐)
If $digits is 0, the number of digits of the mantissa is chosen large enough so that re-reading the printed value with the same precision โ assuming both output and input use rounding to nearest โ will recover the original value of $op. she's thorough like that.
$str will be set to 'Nan', '-Inf' or 'Inf' whenever $op is (respectively) a NaN, a negative infinity or a positive infinity. ๐
Rmpfr_deref2
($str, $si) = Rmpfr_deref2($op, $base, $digits, $rnd);
Returns the mantissa to $str (as a string of base $base digits, prefixed with a minus sign if $op is negative), and returns the exponent to $si as a base 10 value. There's an implicit decimal point to the left of the first digit in $str. $digits specifies the number of digits required to be output in the mantissa.
If $digits is 0, the number of digits of the mantissa is chosen large enough so that re-reading the printed value with the same precision โ assuming both output and input use rounding to nearest โ will recover the original value of $op. โจ
Unlike Rmpfr_get_str() and Rmpfr_integer_string(), $str will be set to '@NaN@', '-@Inf@' or '@Inf@' whenever $op is (respectively) a NaN, a negative infinity or a positive infinity โ because those are the strings that the mpfr library assigns. ๐ค
Rmpfr_integer_string
$str = Rmpfr_integer_string($op, $base, $rnd);
Returns the truncated integer value of $op as a string. (No exponent is returned, nope, none, not today.) For example, if $op contains the value 2.3145679e2, $str will be set to "231".
$str will be set to 'Nan', '-Inf' or 'Inf' whenever $op is (respectively) a NaN, a negative infinity or a positive infinity.
the fits checks ๐ซถ
$bool = Rmpfr_fits_ushort_p($op, $rnd); # fits in unsigned short
$bool = Rmpfr_fits_sshort_p($op, $rnd); # fits in signed short
$bool = Rmpfr_fits_uint_p($op, $rnd); # fits in unsigned int
$bool = Rmpfr_fits_sint_p($op, $rnd); # fits in signed int
$bool = Rmpfr_fits_ulong_p($op, $rnd); # fits in unsigned long
$bool = Rmpfr_fits_slong_p($op, $rnd); # fits in signed long
$bool = Rmpfr_fits_uintmax_p($op, $rnd); # fits in uintmax_t
$bool = Rmpfr_fits_intmax_p($op, $rnd); # fits in intmax_t
$bool = Rmpfr_fits_IV_p($op, $rnd); # fits in perl IV or UV
Return non-zero if $op would fit in the respective data type, when rounded to an integer in the direction $rnd. simple as that bestie ๐
pulling plain numbers back out
$ui = Rmpfr_get_ui($op, $rnd);
$si = Rmpfr_get_si($op, $rnd);
$sj = Rmpfr_get_sj($op, $rnd); # Available only when ivtype is 'long long'.
$uj = Rmpfr_get_uj($op, $rnd); # Available only when ivtype is 'long long'.
$IV = Rmpfr_get_IV($op, $rnd); # $IV is $Config{ivtype}
Convert $op to an 'unsigned long long', a 'signed long', a 'signed long long', an 'unsigned long long' or an 'IV' โ after rounding it with respect to $rnd.
If $op is NaN, the result is undefined. ๐จ If $op is too big for the return type, it returns the maximum or the minimum of the corresponding C type, depending on the direction of the overflow. The flag erange is then also set.
floats, long doubles and the whole extended family
$double = Rmpfr_get_d($op, $rnd);
$ld = Rmpfr_get_ld($op, $rnd);
$f128 = Rmpfr_get_float128($op, $rnd);# nvtype is __float128
# && mpfr-4.0.0 or later
# && mpfr lib built with
# --enable-float128.
$NV = Rmpfr_get_NV ($op, $rnd); # double/long double/__float128
$NV = Rmpfr_get_flt ($op, $rnd); # mpfr-3.0.0 and later.
# Set $NV to $op rounded to float.
$NV = Rmpfr_get_float16($op, $rnd); # mpfr-4.3.0 and later, and
# only on 64-bit systems.
$NV = Rmpfr_get_bfloat16($op, $rnd); # mpfr-4.3.0 and later, and
# only on 64-bit systems.
Rmpfr_get_FLT($FLT, $op, $rnd); # Set the Math::Float32 object $FLT
# to the float value of $op.
Rmpfr_get_FLOAT16($F16, $op, $rnd); # Set the Math::Float16 object $F16
# to the _Float16 value of $op.
Rmpfr_get_BFLOAT16($F16, $op, $rnd); # Set the Math::Bfloat16 object $F16
# to the __bf16 value of $op.
Rmpfr_get_LD($LD, $op, $rnd); # $LD is a Math::LongDouble object.
Rmpfr_get_DECIMAL64($d64, $op, $rnd); # mpfr-3.1.0 or later &&
# mpfr lib built with
# --enable-decimal-float
# && D64=1 arg given to
# Makefile.PL. $D64 is a
# Math::Decimal64 object
Rmpfr_get_FLOAT128($F128, $op, $rnd);# mpfr-4.0.0 and later &&
# mpfr library built with
# --enable-float128.
# $F128 is a Math::Float128
# object.
Convert $op to a 'double', a 'long double', a '__float128', an 'NV', a 'float', a '_Float16', a '__bf16', a Math::Float32 object, a Math::Float16 object, a Math::Bfloat16 object, a Math::LongDouble object, a Math::Decimal64 object, or a Math::Float128 object โ using the rounding mode $rnd. ๐
Rmpfr_get_float16 and Rmpfr_get_bfloat16 are currently unavailable to 32-bit systems. Where they are enabled they actually return an NV that has been set to the exact value of $op rounded (according to $rnd) to a _Float16 or (respectively) a __bf16. ๐ฆ
Rmpfr_get_d1
$double = Rmpfr_get_d1($op);
Convert $op to a double, using the default MPFR rounding mode.
โ ๏ธ THIS FUNCTION IS DEPRECATED. it's giving legacy. Instead, do: code $double = Rmpfr_get_d($op, Rmpfr_get_default_prec());
Rmpfr_get_z_exp / Rmpfr_get_z_2exp
$si = Rmpfr_get_z_exp($z, $op); # $z is a mpz object
$si = Rmpfr_get_z_2exp($z, $op); # $z is a mpz object
(Identical functions. Use either โ 'get_z_exp' might one day be removed. ๐)
Puts the mantissa of $rop into $z, and returns the exponent $si such that $rop == $z * (2 ** $ui).
$inex = Rmpfr_get_z($z, $op, $rnd); # $z is a mpz object.
Convert $op into an mpz object ($z), after rounding it according to $rnd. If you built against mpfr-3.0.0 or later, you get the usual ternary value back ๐. (If you're on mpfr-2.x.x this one just hands you undef โ tragic, we know.) And if $op is NaN or Inf? It croaks with a whole error message about it, no cap.
$inex = Rmpfr_get_f ($f, $op, $rnd); # $f is a Math::GMPf object.
Convert $op into a mpf_t, after rounding per $rnd. Built against mpfr-3.0.0 or later? You get the usual ternary value bestie โจ. Built against earlier mpfr? You get zero when nothing went wrong. Same deal as always: NaN or Inf makes it croak.
Rmpfr_get_q ($q, $op); # $q is a Math::GMPq object.
Convert $op into a rational value. $q gets set to the exact value sitting inside $op โ which is the whole reason there's no rounding argument here ๐
. NaN or Inf โ croak. Periodt.
$d = Rmpfr_get_d_2exp ($exp, $op, $rnd); # $d is NV (double)
$d = Rmpfr_get_ld_2exp ($exp, $op, $rnd); # $d is NV (long double)
Sets $exp and $d so that 0.5<=abs($d)<1 and $d times 2 raised to the power $exp equals $op rounded to double (resp. long double) precision, using the rounding mode you handed it. If $op is zero, you get back a zero of the same sign (or an unsigned zero, if the implementation doesn't do signed zeros) and $exp is set to 0 ๐ซถ. If $op is NaN or an infinity, the matching double-precision (resp. long-double-precision) value comes back and $exp is simply undefined โ ignore it, she said what she said.
$inex = Rmpfr_frexp($si, $rop, $op, $rnd); # mpfr-3.1.0 and later only
Sets $si and $rop so that 0.5<=abs($rop)<1 and $rop * (2 ** $si) equals $op rounded to the precision of $rop, using the given rounding mode. If $op is zero, $rop is set to zero (same sign) and $exp is set to 0. If $op is NaN or an infinity, $rop gets set to that same value and $exp is meaningless โ literally ignore it ๐.
$ui1 = Rmpfr_get_str_ndigits($ui2, $ui3); # new with mpfr-4.1.0
- Note:
$ui2has to land in the range2..62(inclusive), no exceptions bestie. - Returns the minimal integer
$ui1such that any number of precision$ui3bits, when output with$ui1digits in radix$ui2and rounded to nearest, can be recovered exactly when read back in, still rounding to nearest ๐. - More precisely:
$ui1 = 1 + ceil($ui3 * log(2) / log($ui2)), with$ui3decremented by 1 whenever$ui2is a power of 2 โจ. - This wraps
mpfr_get_str_ndigitswhen your mpfr is 4.1.0 or later. Otherwise it callsRmpfr_get_str_ndigits_alt, which doesn't need mpfr-4.1.0 at all.
$ui1 = Rmpfr_get_str_ndigits_alt($ui2, $ui3);
This one's the fallback (though you can absolutely call it on its own too ๐) for Rmpfr_get_str_ndigits when the mpfr version is older than 4.1.0. Unlike Rmpfr_get_str_ndigits, it does not demand that $ui2 sits in the range 2..62.
##########
๐ฅ ARITHMETIC ๐ฅ
$inex = Rmpfr_add($rop, $op1, $op2, $rnd);
$inex = Rmpfr_add_ui($rop, $op, $ui, $rnd);
$inex = Rmpfr_add_si($rop, $op, $si1, $rnd);
$inex = Rmpfr_add_d($rop, $op, $double, $rnd);
$inex = Rmpfr_add_z($rop, $op, $z, $rnd); # $z is a mpz object.
$inex = Rmpfr_add_q($rop, $op, $q, $rnd); # $q is a mpq object.
Sets $rop to 2nd arg + 3rd arg, rounded in the direction $rnd ๐ซ. The return value is zero when $rop is exactly 2nd arg + 3rd arg, positive when $rop is bigger than that, and negative when $rop is smaller than that. She's very precise about her feelings.
$inex = Rmpfr_sum($rop, \@ops, scalar(@ops), $rnd);
@ops is an array made up entirely of Math::MPFR objects, okay? Sets $rop to the sum of every member of @ops, rounded in the direction $rnd. $si is zero when the computed value is the exact value, and non-zero when that can't be guaranteed โ and note it does not give you the direction of the error like the other functions do. Different vibe, same energy.
$inex = Rmpfr_sub($rop, $op1, $op2, $rnd);
$inex = Rmpfr_sub_ui($rop, $op, $ui, $rnd);
$inex = Rmpfr_sub_z($rop, $op, $z, $rnd); # $z is a mpz object.
$inex = Rmpfr_z_sub($rop, $z, $op, $rnd); # mpfr-3.1.0 and later only
$inex = Rmpfr_sub_q($rop, $op, $q, $rnd); # $q is a mpq object.
$inex = Rmpfr_ui_sub($rop, $ui, $op, $rnd);
$inex = Rmpfr_si_sub($rop, $si1, $op, $rnd);
$inex = Rmpfr_sub_si($rop, $op, $si1, $rnd);
$inex = Rmpfr_sub_d($rop, $op, $double, $rnd);
$inex = Rmpfr_d_sub($rop, $double, $op, $rnd);
Sets $rop to 2nd arg - 3rd arg, rounded in the direction $rnd ๐ธ. Return value is zero when $rop is exactly 2nd arg - 3rd arg, positive when $rop is larger, negative when $rop is smaller. Clock the ordering, bestie โ the ui_sub, si_sub, d_sub and z_sub variants flip who's subtracting who ๐ญ.
$inex = Rmpfr_mul($rop, $op1, $op2, $rnd);
$inex = Rmpfr_mul_ui($rop, $op, $ui, $rnd);
$inex = Rmpfr_mul_si($rop, $op, $si1, $rnd);
$inex = Rmpfr_mul_d($rop, $op, $double, $rnd);
$inex = Rmpfr_mul_z($rop, $op, $z, $rnd); # $z is a mpz object.
$inex = Rmpfr_mul_q($rop, $op, $q, $rnd); # $q is a mpq object.
Sets $rop to 2nd arg * 3rd arg, rounded in the direction $rnd. Returns 0 when the result is exact, a positive value when $rop is greater than 2nd arg times 3rd arg, and a negative value otherwise ๐.
$inex = Rmpfr_div($rop, $op1, $op2, $rnd);
$inex = Rmpfr_div_ui($rop, $op, $ui, $rnd);
$inex = Rmpfr_ui_div($rop, $ui, $op, $rnd);
$inex = Rmpfr_div_si($rop, $op, $si1, $rnd);
$inex = Rmpfr_si_div($rop, $si1, $op, $rnd);
$inex = Rmpfr_div_d($rop, $op, $double, $rnd);
$inex = Rmpfr_d_div($rop, $double, $op, $rnd);
$inex = Rmpfr_div_z($rop, $op, $z, $rnd); # $z is a mpz object.
$inex = Rmpfr_z_div($rop, $z, $op, $rnd); # $z is a mpz object.
$inex = Rmpfr_div_q($rop, $op, $q, $rnd); # $q is a mpq object.
$inex = Rmpfr_q_div($rop, $q, $op, $rnd); # $q is a mpq object.
NOTE: The mpfr library does not providempfr_z_divandmpfr_q_divfunctions. That's on Math::MPFR, not on mpfr, iykyk ๐ง.
Sets $rop to 2nd arg / 3rd arg, rounded in the direction $rnd. These return 0 when the division is exact, a positive value when $rop is larger than 2nd arg divided by 3rd arg, and a negative value otherwise.
q_add_fr($q1, $q2, $op); # $q1, $q2 are mpq objects
Sets $q1 to the exact rational value of $q2 + $op ๐.
q_sub_fr($q1, $q2, $op); # $q1, $q2 are mpq objects
Sets $q1 to the exact rational value of $q2 - $op.
q_mul_fr($q1, $q2, $op); # $q1, $q2 are mpq objects
Sets $q1 to the exact rational value of $q2 * $op.
q_div_fr($q1, $q2, $op); # $q1, $q2 are mpq objects
Sets $q1 to the exact rational value of $q2 % $op.
q_fmod_fr($q1, $q2, $op); # $q1, $q2 are mpq objects
Sets $q1 to the exact rational value of fmod($q2,$op).
$inex = Rmpfr_sqr($rop, $op, $rnd);
Sets $rop to the square of $op, rounded in direction $rnd โจ.
$inex = Rmpfr_sqrt($rop, $op, $rnd);
$inex = Rmpfr_sqrt_ui($rop, $ui, $rnd);
Sets $rop to the square root of the 2nd arg, rounded in the direction $rnd. And heads up โ $rop gets set to NaN if the 2nd arg is negative ๐ญ. Returns 0 when the operation is exact, a non-zero value otherwise.
$inex = Rmpfr_rec_sqrt($rop, $op, $rnd);
Sets $rop to $op ** (-1 / 2) rounded in the direction $rnd. Sets $rop to +Inf when $op is 0, and to 0 when $op is +Inf. And sets $rop to NaN when $op is less than zero ๐.
$inex = Rmpfr_rec_root($rop, $op, $ui, $rnd);
NOTE: There is no such mpfr function asmpfr_rec_root. This one started life as a perl implementation by Vincent Lefevre โ and was rewritten by sisyphus as an XSub. (Seehttps://sympa.inria.fr/sympa/arc/mpfr/2016-12/msg00032.htmlfor the receipts ๐ .)
Sets $rop to $op ** (-1 / $ui) rounded in the direction $rnd. This function sets its $rop to the reciprocal of the $rop that Rmpfr_rootn_ui (below) sets for identical arguments. And fair warning: it may not correctly handle overflow or underflow ๐ซถ.
$inex = Rmpfr_cbrt($rop, $op, $rnd);
Sets $rop to the cubic root of $op, rounded in the direction $rnd.
$inex = Rmpfr_root($rop, $op, $ui $rnd);
Deprecated as of mpfr-4.0.0 โ use Rmpfr_rootn_ui with mpfr-4 and later, bestie, this one's on its way out ๐. It'll croak with a "deprecation" warning if Math::MPFR was built against mpfr-4.x.x or later. Sets $rop to the $ui'th root of $op, rounded in the direction $rnd. Returns 0 when the operation is exact, a non-zero value otherwise.
$inex = Rmpfr_rootn_ui($rop, $op, $ui $rnd); # mpfr-4.0.0 and later
Same as Rmpfr_root except $rop gets set to +0 (instead of -0) when $op is -0 and $ui is even. That one-character difference is the whole plot twist ๐. This function (and Rmpfr_cbrt) agrees with the rootn function of the IEEE 754-2008 standard (Section 9.2) ๐.
$inex = Rmpfr_pow_ui($rop, $op, $ui, $rnd);
$inex = Rmpfr_pow_uj($rop, $op, $uj, $rnd);
$inex = Rmpfr_pow_si($rop, $op, $si, $rnd);
$inex = Rmpfr_pow_sj($rop, $op, $sj, $rnd);
$inex = Rmpfr_pown($rop, $op, $sj, $rnd); # same as Rmpfr_pow_sj
$inex = Rmpfr_ui_pow_ui($rop, $ui, $ui, $rnd);
$inex = Rmpfr_ui_pow($rop, $ui, $op, $rnd);
$inex = Rmpfr_pow ($rop, $op1, $op2, $rnd);
$inex = Rmpfr_pow_z ($rop, $op, $z, $rnd); # $z is a mpz object
$inex = Rmpfr_pow_IV($rop, $op, $IV, $rnd); # $IV is $Config{ivtype}
Sets $rop to 2nd arg raised to the 3rd arg, rounded in the direction $rnd with the precision of $rop. Returns zero when the result is exact, a positive value when the result is greater than 2nd arg to the power 3rd arg, and a negative value when it's smaller. For the special cases (aka when nan or signed inf/zero values are in the mix ๐) go read the MPFR documentation โ she's not about to improvise those.
$inex = Rmpfr_powr($rop, $op1, $op2, $rnd);
Corresponds to the powr function from IEEE 754: $rop = exp($op2 * log($op1)) rounded in the direction $rnd with the precision of $rop ๐.
$inex = Rmpfr_compound ($rop, $op1, $op2, $rnd); # New in 4.3.0
$inex = Rmpfr_compound_si($rop, $op1, $si, $rnd); # New in 4.2.0
$rop = ($op1 + 1) ** 3rd_arg, rounded according to $rnd, to the precision of $rop. But there are special cases, and they're kind of a lot:
$ropis set to NaN when$op1 < -1;$ropis set to 1 when$op1is NaN and$op2is 0;$ropis set to+Infwhen$op1is -1 and$op2 < 0;$ropis set to+0when$op1is -1 and$op2 > 0.- The other special cases follow the
Rmpfr_powrules on(1 + OP1, OP2).
$inex = Rmpfr_neg($rop, $op, $rnd);
Sets $rop to -$op rounded in the direction $rnd. And here's the cute part โ if $rop and $op are the same variable, it literally just changes the sign ๐. In-place queen behavior.
$inex = Rmpfr_abs($rop, $op, $rnd);โ sets$ropto the absolute value of$op, rounded in the direction$rnd. Returns0if the result is exact, a positive value if$ropis larger than the absolute value of$op, and a negative value otherwise ๐$inex = Rmpfr_dim($rop, $op1, $op2, $rnd);โ sets$ropto the positive difference of$op1and$op2, i.e.$op1 - $op2rounded in the direction$rndif$op1 > $op2, and+0otherwise. And heads up bestie:$ropgets set to NaN when$op1or$op2is NaN ๐- the
Rmpfr_mul_2exp/Rmpfr_mul_2ui/Rmpfr_mul_2sitrio ๐ง
$inex = Rmpfr_mul_2exp($rop, $op, $ui, $rnd);
$inex = Rmpfr_mul_2ui($rop, $op, $ui, $rnd);
$inex = Rmpfr_mul_2si($rop, $op, $si, $rnd);
Sets $rop to 2nd arg times 2 raised to 3rd arg, rounded to the direction $rnd. When $rop and 2nd arg are identical it literally just bumps the exponent by the 3rd arg. Returns zero when $rop = 2nd arg, a positive value when $rop > 2nd arg, and a negative value when $rop < 2nd arg.
Note: TheRmpfr_mul_2expfunction is defined for compatibility reasons; you should useRmpfr_mul_2ui(orRmpfr_mul_2si) instead. Like, it's giving legacy energy ๐
- the
Rmpfr_div_2exp/Rmpfr_div_2ui/Rmpfr_div_2sitrio ๐ฆ
$inex = Rmpfr_div_2exp($rop, $op, $ui, $rnd);
$inex = Rmpfr_div_2ui($rop, $op, $ui, $rnd);
$inex = Rmpfr_div_2si($rop, $op, $si, $rnd);
Sets $rop to 2nd arg divided by 2 raised to 3rd arg, rounded to the direction $rnd. When $rop and 2nd arg are identical it just decreases the exponent by the 3rd arg. Returns zero when $rop = 2nd arg, a positive value when $rop > 2nd arg, and a negative value when $rop < 2nd arg.
Note: TheRmpfr_div_2expfunction is defined for compatibility reasons; you should useRmpfr_div_2ui(orRmpfr_div_2si) instead. Same old-school situation, no cap.
๐ COMPARISON ๐
- the whole
Rmpfr_cmpsquad ๐
$si = Rmpfr_cmp($op1, $op2);
$si = Rmpfr_cmpabs($op1, $op2);
$si = Rmpfr_cmpabs_ui($op, $ui); # requires mpfr-4.1.0 and later
$si = Rmpfr_cmp_ui($op, $ui);
$si = Rmpfr_cmp_si($op, $si);
$si = Rmpfr_cmp_d($op, $double);
$si = Rmpfr_cmp_ld($op, $ld); # long double
$si = Rmpfr_cmp_float128($op, $f128); # __float128
$si = Rmpfr_cmp_z($op, $z); # $z is a mpz object
$si = Rmpfr_cmp_q($op, $q); # $q is a mpq object
$si = Rmpfr_cmp_f($op, $f); # $f is a mpf object
$si = Rmpfr_cmp_IV($op, $iv); # $iv is $Config{ivtype}
$si = Rmpfr_cmp_NV($op, $nv); # $nv is $Config{nvtype}
$si = Rmpfr_cmp_str($op, $str);
Compares 1st and 2nd args. In the case of Rmpfr_cmpabs() and Rmpfr_cmpabs_ui it compares the absolute values of the 2 args. Returns a positive value if 1st arg > 2nd arg, zero if 1st arg = 2nd arg, and a negative value if 1st arg < 2nd arg. Both args are considered to their full own precision, which may differ. ($str will be compared at infinite precision โ iconique.) In case 1st and 2nd args are of same sign but different, the absolute value returned is one plus the absolute difference of their exponents. If one of the operands is NaN (Not-a-Number), it returns zero and sets the erange flag. ๐
NOTE: 1.Rmpfr_cmp_IV()requires that the 2nd argument has itsIOKflag set, andRmpfr_cmp_NV()requires that the 2nd argument has itsNOKflag set. Otherwise these functions croak. Suggestion: first check the status of the flag usingIOK_flag($iv)orNOK_flag($nv), which return a non-zero value if and only if the flag in question is set. 2.Rmpfr_cmp_IVhandles both signed and unsignedIVargs.
$si = fr_cmp_q_rounded($op, $q, $rnd); # $q is a mpq objectโ converts$qto an mpfr object of current default precision, rounded in accordance with the value specified by$rnd. Then compares$opwith this mpfr object, according to the rules specified forRmpfr_cmp(above). Glow-up first, then compare โจ$bool = Rmpfr_total_order_p($op1, $op2); # new with mpfr-4.1.0โ this one implements thetotalOrderpredicate from IEEE 754-2008, where-NaN < -Inf < negative finite numbers < -0 < +0 < positive finite numbers < +Inf < +NaN. It returns a non-zero value (true) when X is smaller than or equal to Y for this order relation, and zero (false) otherwise. Contrary toRmpfr_cmp($x, $y), which returns a ternary value,Rmpfr_total_order_preturns a binary value (zero or non-zero). In particular,Rmpfr_total_order_p($x, $x)returns true,Rmpfr_total_order_p(-0, +0)returns true andRmpfr_total_order_p(+0, -0)returns false. The sign bit of NaN also matters. This function falls back to our own implementation if the mpfr version is older than 4.1.0 (because, in that case,mpfr_total_order_pis unavailable). ๐ซถ- the
2expcomparison duo ๐
$si = Rmpfr_cmp_ui_2exp($op, $ui, $si);
$si = Rmpfr_cmp_si_2exp($op, $si, $si);
Compares 1st arg and 2nd arg multiplied by two to the power 3rd arg.
$bool = Rmpfr_eq($op1, $op2, $ui);โ head's up, the mpfr library functionmpfr_eqmay change in future releases of the mpfr library (post 2.4.0). If that happens, the change will also be reflected inRmpfr_eq. Returns non-zero if the first$uibits of$op1and$op2are equal, zero otherwise. I.e., tests if$op1and$op2are approximately equal. It's giving "close enough bestie" ๐$bool = Rmpfr_nan_p($op);โ returns non-zero if$opis Not-a-Number (NaN), zero otherwise.$bool = Rmpfr_inf_p($op);โ returns non-zero if$opis plus or minus infinity, zero otherwise.$bool = Rmpfr_number_p($op);โ returns non-zero if$opis an ordinary number, i.e. neither Not-a-Number nor plus or minus infinity.$bool = Rmpfr_zero_p($op);โ returns non-zero if$opis zero. Else returns0.$bool = Rmpfr_regular_p($op); # mpfr-3.0.0 and later onlyโ returns non-zero if$opis a regular number (i.e. neither NaN, nor an infinity nor zero). Returns zero otherwise.Rmpfr_reldiff($rop, $op1, $op2, $rnd);โ computes the relative difference between$op1and$op2and stores the result in$rop. Real talk: this function does not guarantee the exact rounding on the relative difference; it just computesabs($op1-$op2)/$op1, using the rounding mode$rndfor all operations. ๐ญ$si = Rmpfr_sgn($op);โ returns a positive value if op > 0, zero if$op = 0, and a negative value if$op < 0. Its result is not specified when$opis NaN (Not-a-Number). So like, don't. ๐$bool = Rmpfr_greater_p($op1, $op2);โ returns non-zero if$op1 > $op2, zero otherwise.$bool = Rmpfr_greaterequal_p($op1, $op2);โ returns non-zero if$op1 >= $op2, zero otherwise.$bool = Rmpfr_less_p($op1, $op2);โ returns non-zero if$op1 < $op2, zero otherwise.$bool = Rmpfr_lessequal_p($op1, $op2);โ returns non-zero if$op1 <= $op2, zero otherwise.$bool = Rmpfr_lessgreater_p($op1, $op2);โ returns non-zero if$op1 < $op2or$op1 > $op2(i.e. neither$op1, nor$op2is NaN, and$op1 <> $op2), zero otherwise (i.e.$op1and/or$op2are NaN, or$op1 = $op2).$bool = Rmpfr_equal_p($op1, $op2);โ returns non-zero if$op1 = $op2, zero otherwise (i.e.$op1and/or$op2are NaN, or$op1 <> $op2).$bool = Rmpfr_unordered_p($op1, $op2);โ returns non-zero if$op1or$op2is a NaN (i.e. they cannot be compared), zero otherwise. Chaos energy fr fr ๐ช๏ธ
โจ SPECIAL โจ
- the log duo that overloading would use ๐
$rop = log_2 ($op);
$rop = log_10($op);
Returns log2 of $op (resp. log10 of $op), set to default precision and using default rounding mode. These are the functions that log2 and log10 overloading would call if log2 and log10 overloading was available.
- the
Rmpfr_logfamily ๐ธ
$inex = Rmpfr_log($rop, $op, $rnd);
$inex = Rmpfr_log_ui($rop, $ui, $rnd); # mpfr-4.0.0 & later only
$inex = Rmpfr_log2($rop, $op, $rnd);
$inex = Rmpfr_log10($rop, $op, $rnd);
Sets $rop to the natural logarithm of $op, the natural logarithm of $ui, log2($op) or log10($op), respectively, rounded in the direction $rnd.
- the
Rmpfr_expfamily ๐ฅ
$inex = Rmpfr_exp($rop, $op, $rnd);
$inex = Rmpfr_exp2($rop, $op, $rnd);
$inex = Rmpfr_exp10($rop, $op, $rnd);
Sets rop to the exponential of op, to 2 power of op or to 10 power of op, respectively, rounded in the direction rnd.
$rop = sind($op); # Value of $op is in degrees (not radians)and$rop = cosd($op); # Value of $op is in degrees (not radians)โ return (respectively)sin()andcos()of$op, where the value of$opis expressed in degrees. The return value is calculated using default precision and default rounding mode. These are essentially the same as the overloadedsinandcosfunctions except that the given argument is in degrees. Degrees bestie, not radians ๐ฆ$rop = tand($op); # $op is in degrees (not radians)and$rop = tangent($op); # $op is in radiansโ returnstan($op)calculated with default precision and default rounding mode. Yes both exist and yes the units differ, read the comments ๐- the sin/cos/tan trio โญ
$inex = Rmpfr_sin($rop $op, $rnd);
$inex = Rmpfr_cos($rop, $op, $rnd);
$inex = Rmpfr_tan($rop, $op, $rnd);
Sets $rop to the sine/cosine/tangent respectively of $op, rounded to the direction $rnd with the precision of $rop. Returns 0 if the result is exact (this occurs in fact only when $op is 0, i.e. the sine is 0, the cosine is 1, and the tangent is 0). Returns a negative value if the result is less than the actual value. Returns a positive result if the return is greater than the actual value.
$si = Rmpfr_sin_cos($rop1, $rop2, $op, $rnd);โ sets simultaneously$rop1to the sine of$opand$rop2to the cosine of$op, rounded to the direction$rndwith their corresponding precisions. Returns0if both results are exact. Two for one, obsessed ๐- the
u-suffixed trig trio (the Pi-flavoured ones) ๐ฅง
$inex = Rmpfr_cosu($rop, $op, $ui, $rnd); # mpfr-4.2.0 and later only
$inex = Rmpfr_sinu($rop, $op, $ui, $rnd); # mpfr-4.2.0 and later only
$inex = Rmpfr_tanu($rop, $op, $ui, $rnd); # mpfr-4.2.0 and later only
Sets $rop to the cosine (resp. sine and tangent) of $op multiplied by 2*Pi and divided by $ui. For example, if $ui equals 360, one gets the cosine (resp. sine and tangent) for $op in degrees. For Rmpfr_cosu, when $op multiplied by 2 and divided by $ui is a half-integer, the result is +0, following IEEE 754-2019 (cosPi), so that the function is even. For Rmpfr_sinu, when $op multiplied by 2 and divided by $ui is an integer, the result is zero with the same sign as $op, following IEEE 754-2019 (sinPi), so that the function is odd. Similarly, the function Rmpfr_tanu follows IEEE 754-2019 (tanPi).
And here's the equivalence, bestie, write it down:
Rmpfr_cosu/sinu/tanu ($rop, $op, $ui, $rnd) is equivalent to
Rmpfr_cospi/sinpi/tanpi($rop, ($op/$ui)/2, $rnd) below.
$inex = Rmpfr_acosu($rop, $op, $ui, $rnd); # mpfr-4.2.0 and later only
$inex = Rmpfr_asinu($rop, $op, $ui, $rnd); # mpfr-4.2.0 and later only
$inex = Rmpfr_atanu($rop, $op, $ui, $rnd); # mpfr-4.2.0 and later only
okay so this trio?? kind of iconic. They set $rop to X multiplied by $ui and divided by 2*Pi, where X is the arc-cosine (or arc-sine, or arc-tangent, depending on which one you called, bestie, keep up ๐ซถ) of $op.
Like, real talk: if $ui equals 360, mpfr_acosu yields the arc-cosine in degrees. Degrees! We're not stuck in radians anymore, we're โจthrivingโจ.
$inex = Rmpfr_cospi($rop, $op, $rnd); # mpfr-4.2.0 and later only
$inex = Rmpfr_sinpi($rop, $op, $rnd); # mpfr-4.2.0 and later only
$inex = Rmpfr_tanpi($rop, $op, $rnd); # mpfr-4.2.0 and later only
Set $rop to the cosine (or sine, or tangent) of $op multiplied by Pi. For the special values gossip, go peek at the description of Rmpfr_sinu, Rmpfr_cosu and Rmpfr_tanu โ they spill all the tea. ๐ต
And the equivalence, because I know you love a shortcut:
Rmpfr_cospi/sinpi/tanpi($rop, $op, $rnd) is equivalent to Rmpfr_cosu/sinu/tanu ($rop, $op, 2, $rnd) above.
Same energy, different outfit. ๐
$inex = Rmpfr_acospi($rop, $op, $rnd); # mpfr-4.2.0 and later only
$inex = Rmpfr_asinpi($rop, $op, $rnd); # mpfr-4.2.0 and later only
$inex = Rmpfr_atanpi($rop, $op, $rnd); # mpfr-4.2.0 and later only
$rop = acos($op)/Pi, resp. asin($op)/Pi and atan($op)/Pi. Math but make it โจaestheticโจ.
$inex = Rmpfr_sinh_cosh($rop1, $rop2, $op, $rnd);
Not me doing two things at once because I'm a multitasking queen ๐. This sets $rop1 to the hyperbolic sine of $op AND $rop2 to the hyperbolic cosine of $op โ simultaneously, no cap. Both get rounded in the direction $rnd with the corresponding precision of $rop1 and $rop2, which must be different variables. fr fr, they cannot be the same variable, do not try it.
Returns 0 if both results are exact. ๐
$inex = Rmpfr_acos($rop, $op, $rnd);
$inex = Rmpfr_asin($rop, $op, $rnd);
$inex = Rmpfr_atan($rop, $op, $rnd);
Set $rop to the arc-cosine, arc-sine or arc-tangent of $op, rounded to the direction $rnd with the precision of $rop.
The return-value vibe check ๐:
0if the result is exact.- A negative value if the result is less than the actual value.
- A positive result if the return is greater than the actual value.
$inex = Rmpfr_atan2($rop, $op1, $op2, $rnd);
Set $rop to the tangent of $op1/$op2, rounded to the direction $rnd with the precision of $rop.
Same receipts as above, bestie:
0if the result is exact.- A negative value if the result is less than the actual value.
- A positive result if the return is greater than the actual value.
And for the special cases?? See the MPFR documentation for the details. iykyk ๐
$inex = Rmpfr_atan2u($rop, $op1, $op2, $ui, $rnd);
Same as taking the Rmpfr_atan2() result and multiplying it by $ui/(2*Pi). One little glow-up and suddenly we're in different units. โจ
$inex = Rmpfr_atan2pi($rop, $op1, $op2, $rnd);
Same as Rmpfr_atan2u() with $ui = 2. Shoutout to the shortcut kings. ๐
$inex = Rmpfr_cosh($rop, $op, $rnd);
$inex = Rmpfr_sinh($rop, $op, $rnd);
$inex = Rmpfr_tanh($rop, $op, $rnd);
Set $rop to the hyperbolic cosine / hyperbolic sine / hyperbolic tangent respectively of $op, rounded to the direction $rnd with the precision of $rop.
Returns 0 if the result is exact โ and honestly?? that only happens when $op is 0, i.e. the result is 1. Iconic but rare. ๐
- A negative value if the result is less than the actual value.
- A positive result if the return is greater than the actual value.
$inex = Rmpfr_acosh($rop, $op, $rnd);
$inex = Rmpfr_asinh($rop, $op, $rnd);
$inex = Rmpfr_atanh($rop, $op, $rnd);
Set $rop to the inverse hyperbolic cosine, sine or tangent of $op, rounded to the direction $rnd with the precision of $rop. Returns 0 if the result is exact. Short and sweet, we love a low-maintenance function. ๐
$inex = Rmpfr_sec ($rop, $op, $rnd);
$inex = Rmpfr_csc ($rop, $op, $rnd);
$inex = Rmpfr_cot ($rop, $op, $rnd);
Set $rop to the secant of $op, cosecant of $op, cotangent of $op, rounded in the direction RND.
Returns:
0if the result is exact.- A negative value if the result is less than the actual value.
- A positive result if the return is greater than the actual value.
$inex = Rmpfr_sech ($rop, $op, $rnd);
$inex = Rmpfr_csch ($rop, $op, $rnd);
$inex = Rmpfr_coth ($rop, $op, $rnd);
The hyperbolic remix ๐ฆ โ set $rop to the hyperbolic secant of $op, cosecant of $op, cotangent of $op, rounded in the direction RND.
Same three-way return situation:
0if the result is exact.- A negative value if the result is less than the actual value.
- A positive result if the return is greater than the actual value.
(Yes bestie, the secant-versions and the h-versions have literally identical return rules. That's just how the page do. ๐ญ)
$inex = Rmpfr_fac_ui($rop, $ui, $rnd);
Set $rop to the factorial of $ui, rounded to the direction $rnd with the precision of $rop. Factorials, but make them arbitrary precision. Go off. ๐ฅ
$inex = Rmpfr_log1p ($rop, $op, $rnd);
$inex = Rmpfr_log2p1 ($rop, $op, $rnd);
$inex = Rmpfr_log10p1($rop, $op, $rnd);
Three flavors of "log of one plus the thing", and the naming is doing a little bit of chaos on purpose, keep your eyes open ๐:
- In
Rmpfr_log1pset$rop = log( $op + 1). - In
Rmpfr_log2p1set$rop = log2( $op + 1). - In
Rmpfr_log10p1set$rop = log10($op + 1).
In all three cases, round the result in the direction $rnd to the precision of $rop.
Note howlog1phas the1at the front and the others shove it in the middle. That's not a typo, that's just how it is.
$inex = Rmpfr_expm1 ($rop, $op, $rnd);
$inex = Rmpfr_exp2m1 ($rop, $op, $rnd);
$inex = Rmpfr_exp10m1($rop, $op, $rnd);
Same chaotic naming energy, now with exponents ๐:
- In
Rmpfr_expm1, set$ropto the exponential of$opfollowed by a subtraction of 1.$rop = (e ** $op) - 1. - In
Rmpfr_exp2p1, set$rop = (2 ** $op) - 1. - In
Rmpfr_exp10p1, set$rop = (10 ** $op) - 1.
For all three, the result is rounded to the direction $rnd with the precision of $rop.
bestie I'm just the messenger: the calls are namedRmpfr_expm1/Rmpfr_exp2m1/Rmpfr_exp10m1, but the prose calls the last twoRmpfr_exp2p1andRmpfr_exp10p1, and they compute- 1. That's what the page says. Don't @ me. ๐
$inex = Rmpfr_fma($rop, $op1, $op2, $op3, $rnd);
Set $rop to $op1 * $op2 + $op3, rounded to the direction $rnd. Fused multiply-add supremacy, no intermediate rounding drama. ๐
$inex = Rmpfr_fmma($rop, $op1, $op2, $op3, $op4, $rnd);
NOTE: Needs mpfr-4.0.0 or later
Set $rop to $op1 * $op2 + $op3 * $op4, rounded to the direction $rnd. Double the multiply, double the slay. ๐
$inex = Rmpfr_fms($rop, $op1, $op2, $op3, $rnd);
Set $rop to $op1 * $op2 - $op3, rounded to the direction $rnd.
$inex = Rmpfr_fmms($rop, $op1, $op2, $op3, $op4, $rnd);
NOTE: Needs mpfr-4.0.0 or later
Set $rop to $op1 * $op2 - $op3 * $op4, rounded to the direction $rnd.
$inex = Rmpfr_agm($rop, $op1, $op2, $rnd);
Set $rop to the arithmetic-geometric mean of $op1 and $op2, rounded to the direction $rnd with the precision of $rop.
Returns:
zeroif$ropis exact.- A positive value if
$ropis larger than the exact value. - A negative value if
$ropis less than the exact value.
$inex = Rmpfr_hypot ($rop, $op1, $op2, $rnd);
Set $rop to the Euclidean norm of $op1 and $op2, i.e. the square root of the sum of the squares of $op1 and $op2, rounded in the direction $rnd.
Special values are currently handled as described in Section F.9.4.3 of the ISO C99 standard, for the hypot function โ and bestie, note this may change in future versions, so don't build your whole personality on it: If $op1 or $op2 is an infinity, then plus infinity is returned in $rop, even if the other number is NaN. Infinity ate and left no crumbs. ๐ฅ
$inex = Rmpfr_ai($rop, $op, $rnd); # mpfr-3.0.0 and later only
Set $rop to the value of the Airy function Ai on $op, rounded in the direction $rnd.
- When
$opisNaN,$ropis always set toNaN. - When
$opis+Infor-Inf,$ropis+0.
โ ๏ธ Warning from the page itself: The current implementation is not intended to be used with large arguments. It works with$optypically smaller than500. For larger arguments, other methods should be used and will be implemented soon. so likeโฆ stay in your lane, keep it under 500, and we're fine ๐ซถ
$inex = Rmpfr_const_log2($rop, $rnd);
Set $rop to the logarithm of 2 rounded to the direction $rnd with the precision of $rop. This function stores the computed value to avoid another calculation if a lower or equal precision is requested โ i.e. it's caching for you, you're welcome, bestie. โจ
Returns:
zeroif$ropis exact.- A positive value if
$ropis larger than the exact value. - A negative value if
$ropis less than the exact value.
$inex = Rmpfr_const_pi($rop, $rnd);
Set $rop to the value of Pi rounded to the direction $rnd with the precision of $rop. This function uses the Borwein, Borwein, Plouffe formula which directly gives the expansion of Pi in base 16. Pi girlies rise, 3.14159... we see you ๐
Returns:
zeroif$ropis exact.- A positive value if
$ropis larger than the exact value. - A negative value if
$ropis less than the exact value.
$inex = Rmpfr_const_euler($rop, $rnd);
Set $rop to the value of Euler's constant 0.577... rounded to the direction $rnd with the precision of $rop.
Returns:
zeroif$ropis exact.- A positive value if
$ropis larger than the exact value. - A negative value if
$ropis less than the exact value.
inex = Rmpfr_const_catalan($rop, $rnd);
Set $rop to the value of Catalan's constant 0.915... rounded to the direction $rnd with the precision of $rop.
Returns:
zeroif$ropis exact.- A positive value if
$ropis larger than the exact value. - A negative value if
$ropis less than the exact value.
(and yes, the return variable here is literally written inex, not $inex. that's the page, that's the vibe, we move ๐
)
Rmpfr_free_cache();
Free the cache used by the functions computing constants if needed โ currently mpfr_const_log2, mpfr_const_pi and mpfr_const_euler. Housekeeping slay ๐งนโจ
Rmpfr_free_cache2($ui); # mpfr-4.0.0 and later only
Free various caches and pools used by MPFR internally, as specified by $ui, which is a set of flags:
- a) those local to the current thread if flag
MPFR_FREE_LOCAL_CACHEis set; - b) those shared by all threads if flag
MPFR_FREE_GLOBAL_CACHEis set.
The other bits of $ui are currently ignored and are reserved for future use; they should be zero. zero them, bestie, fr fr.
Note:Rmpfr_free_cache2(MPFR_FREE_LOCAL_CACHE|MPFR_FREE_GLOBAL_CACHE)is currently equivalent tompfr_free_cache().
Rmpfr_free_pool() # mpfr-4.0.0 and later only
Free the pools used by mpfr internally.
Note: This function is automatically called after the thread-local caches are freed (withmpfr_free_cacheormpfr_free_cache2). So generous, it does itself. ๐
$inex = Rmpfr_beta($rop, $op1, $op2, $rnd); # mpfr-4.0.0 &
# later only
Set $rop to the beta function at $op1, $op2, rounded according to $rnd. Note the slightly topsy line-continuation comment in the synopsis โ it wraps mid-comment and that's just how the source rolls. ๐
$inex = Rmpfr_gamma($rop, $op, $rnd);
$inex = Rmpfr_lngamma($rop, $op, $rnd);
Set $rop to the value of the Gamma function on $op (and, respectively, its natural logarithm) rounded to the direction $rnd.
Returns:
zeroif$ropis exact.- A positive value if
$ropis larger than the exact value. - A negative value if
$ropis less than the exact value.
๐จ Heads up: Rmpfr_gamma sets $rop to NaN when $op is negative. No negative vibes allowed in the Gamma function, apparently. ๐
โโ๏ธ
Okay bestie, we're still deep in function city, and this batch is giving โจspecial functionsโจ, I/O realness, and a lil exception moment. Buckle up, hydrate, and let's go. ๐
$inex = Rmpfr_gamma_inc($rop, $op1, $op2, $rnd);โ mpfr-4.0.0 & later only</p>.
Sets $rop to the value of the incomplete Gamma function on $op1 and $op2, rounded in the direction $rnd.
When $op2 is zero and $op1 is a negative value, $rop is set to NaN.
Note: the current implementation is slow for large values of$ropand$op, in which case some internal overflow might also occur. ๐ญ
($signp, $si) = Rmpfr_lgamma ($rop, $op, $rnd);
Sets $rop to the value of the logarithm of the absolute value of the gamma function on $op, rounded in the direction $rnd. The sign (1 or -1) of gamma($op) is returned in $signp. When $op is an infinity or a non-positive integer, +Inf is returned. When $op is NaN, -Inf or a negative integer, $signp is undefined, and when $op is 0, $signp is the sign of the zero.
$inex = Rmpfr_digamma($rop, $op, $rnd);โ mpfr-3.0.0 and later only</p>.
Sets $rop to digammma($op), rounded according to $rnd.
$inex = Rmpfr_trigamma ($rop, $op, $rnd);โ mpfr-4.3.0 and later only</p>.
Sets $rop to trigammma($op), rounded according to $rnd.
$inex = Rmpfr_zeta($rop, $op, $rnd);$inex = Rmpfr_zeta_ui($rop, $ul, $rnd);
These set $rop to the value of the Riemann Zeta function on 2nd arg, rounded to the direction $rnd. Return zero if $rop is exact, a positive value if $rop is larger than the exact value, or a negative value if $rop is less than the exact value.
$inex = Rmpfr_erf($rop, $op, $rnd);
Sets $rop to the value of the error function on $op, rounded to the direction $rnd. Return zero if $rop is exact, a positive value if $rop is larger than the exact value, or a negative value if $rop is less than the exact value.
$inex = Rmpfr_erfc($rop, $op, $rnd);
Sets $rop to the value of the complementary error function on $op, rounded to the direction $rnd. Return zero if $rop is exact, a positive value if $rop is larger than the exact value, or a negative value if $rop is less than the exact value.
$inex = Rmpfr_j0 ($rop, $op, $rnd);$inex = Rmpfr_j1 ($rop, $op, $rnd);$inex = Rmpfr_jn ($rop, $si2, $op, $rnd);
These set $rop to the value of the first order Bessel function of order 0, 1 and $si2 on $op, rounded in the direction $rnd. When $op is NaN, $rop is always set to NaN. When $op is plus or minus Infinity, $rop is set to +0. When $op is zero, and $si2 is not zero, $rop is +0 or -0 depending on the parity and sign of $si2, and the sign of $op.
$inex = Rmpfr_y0 ($rop, $op, $rnd);$inex = Rmpfr_y1 ($rop, $op, $rnd);$inex = Rmpfr_yn ($rop, $si2, $op, $rnd);
These set $rop to the value of the second order Bessel function of order 0, 1 and $si2 on $op, rounded in the direction $rnd. When $op is NaN or negative, $rop is always set to NaN. When $op is +Inf, $rop is +0. When $op is zero, $rop is +Inf or -Inf depending on the parity and sign of $si2.
$inex = Rmpfr_eint ($rop, $op, $rnd)โ yes, no semicolon, that's how it's written.
Sets $rop to the exponential integral of $op, rounded in the direction $rnd. See the MPFR documentation for details. As of mpfr-4.0.0 Rmpfr_eint() returns the value of the E1/eint1 function for negative input. (With previous versions of mpfr NaN was returned for negative argument.)
$inex = Rmpfr_li2 ($rop, $op, $rnd);
Sets $rop to real part of the dilogarithm of $op, rounded in the direction $rnd. The dilogarithm function is defined here as the integral of -log(1-t)/t from 0 to x.
$inex = Rmpfr_dot ($rop, \@op1, \@op2, $ui, $rnd);โ mpfr-4.1.0 & later only</p>.
Sets $rop to the dot product of elements of @op1 by those of @op2, whose common size is $ui (== scalar @op1), correctly rounded in the direction $rnd.
This function is experimental, and does not yet handle intermediate overflows and underflows.
๐พ I-O FUNCTIONS ๐พ
$ui = Rmpfr_out_str([$prefix,] $op, $base, $digits, $round [, $suffix]);โ BEST TO USETRmpfr_out_strINSTEAD.
Outputs $op to STDOUT, as a string of digits in base $base, rounded in direction $round. $base may be in the range 2 to 62 (or -36..-2, 2 .. 62 if Math::MPFR has been built against mpfr-4.1.0 or later).
Print $digits significant digits exactly, or if $digits is 0, enough digits so that $op can be read back exactly (see Rmpfr_get_str). In addition to the significant digits, a decimal point at the right of the first digit and a trailing exponent in base 10, in the form 'eNNN', are printed. If $base is greater than 10, '@' will be used instead of 'e' as exponent delimiter. The optional arguments, $prefix and $suffix, are strings that will be prepended/appended to the mpfr_out_str output. Return the number of bytes written (not counting those contained in $suffix and $prefix), or if an error occurred, return 0. (Note that none, one or both of $prefix and $suffix can be supplied.)
$ui = TRmpfr_out_str([$prefix,] $stream, $base, $digits, $op, $round [, $suffix]);
As for Rmpfr_out_str, except that there's the capability to print to somewhere other than STDOUT. Note that the order of the args is different (to match the order of the mpfr_out_str args).
To print to STDERR:
TRmpfr_out_str(*stderr, $base, $digits, $op, $round);
To print to an open filehandle (let's call it $fh):
TRmpfr_out_str(\*$fh, $base, $digits, $op, $round);
$ui = Rmpfr_inp_str($rop, $base, $round);โ BEST TO USETRmpfr_inp_strINSTEAD.
Input a string in base $base from STDIN, rounded in direction $round, and put the read float in $rop. The string is of the form 'M@N' or, if the base is 10 or less, alternatively 'MeN' or 'MEN', or, if the base is 16, alternatively 'MpB' or 'MPB'. 'M' is the mantissa in the specified base, 'N' is the exponent written in decimal for the specified base, and in base 16, 'B' is the binary exponent written in decimal (i.e. it indicates the power of 2 by which the mantissa is to be scaled). The argument $base may be in the range 2 to 62.
Special values can be read as follows (the case does not matter): '@NaN@', '@Inf@', '+@Inf@' and '-@Inf@', possibly followed by other characters; if the base is smaller or equal to 16, the following strings are accepted too: 'NaN', 'Inf', '+Inf' and '-Inf'.
Return the number of bytes read, or if non-numeric characters were encountered in the input, return 0.
If 0 is returned:
- the non-numeric flag (which was initialised to
0) will be incremented. You can query/clear/reset the value of the flag with (resp.)nnumflag()/clear_nnum()/set_nnum()- all of which are documented below; - A warning will be emitted if
$Math::MPFR::NNWis set to1(default is0).
$ui = TRmpfr_inp_str($rop, $stream, $base, $round);
As for Rmpfr_inp_str, except that there's the capability to read from somewhere other than STDIN.
To read from STDIN:
TRmpfr_inp_str($rop, *stdin, $base, $round);
To read from an open filehandle (let's call it $fh):
TRmpfr_inp_str($rop, \*$fh, $base, $round);
Rmpfr_dump($op);
Outputs "$op\n" on stdout in base 2. As with 'Rmpfr_print_binary' the exponent is in base 10.
$si = Rmpfr_fpif_export ($stream, $op);โ Needsmpfr-4.0.0</p>.$si = Rmpfr_fpif_import ($op, $stream);โ Needsmpfr-4.0.0</p>.$si = Rmpfr_fpif_export_mem ($buf, $bufsize, $op);โ Needsmpfr-4.3.0</p>.$si = Rmpfr_fpif_import_mem ($op, $buf, $bufsize);โ Needsmpfr-4.3.0</p>.
Note: These functions are experimental and their interface might change in future versions of mpfr.
Export/import the number $op to/from the stream/string $stream/$buf in a floating-point interchange format. The import function fails if the precision (which is read from the stream/string) is greater than RMPFR_PREC_MAX. Return 0 if the export/import was successful.
For the two *_mem functions, $buf is a perl variable (SV) that does not need to have been initialized. $bufsize needs to be sufficiently large to accommodate the output of the function. You can calculate the minimum $bufsize with:
$size = Rmpfr_fpif_size($op);
$bufsize = Rmpfr_fpif_size($op) + 1; # Include the terminating
# NULL byte
Or, simply call the functions as:
$si = Rmpfr_fpif_export_mem($buf, Rmpfr_fpif_size($op)+1, $op);
$si = Rmpfr_fpif_import_mem($rop, $buf, length($buf));
$ui = Rmpfr_fpif_size($op);
Return a satisfactory value for the size of the string buffer needed as 1st arg to Rmpfr_fpif_export_mem() above.
๐ฆ DISPLAYING INFS AND NANS ๐ฆ
Generally, these will be displayed as 'Inf', '-Inf' and 'NaN'. However, if you set $Math::MPFR::PERL_INFNAN to a TRUE value, then nvtoa($num) and numtoa($num) (which are documented below in 'MISCELLANEOUS') will display them in the same way that perl itself displays them.
Note that nvtoa() and numtoa() expect a plain numeric perl scalar as their argument - not a Math::MPFR object.
$Math::MPFR::PERL_INFNAN has the initial (default) value of 0.
๐ EXCEPTIONS ๐
$inex = Rmpfr_subnormalize ($op, $si, $rnd);
This function subnormalizes $op when subnormalization is appropriate. Otherwise $op remains unchanged.
See the MPFR documentation for mpfr_subnormalize at: https://www.mpfr.org/mpfr-current/mpfr.html#index-mpfr_005fsubnormalize
$rop = subnormalize_float32 ($val);$rop = subnormalize_float16 ($val);$rop = subnormalize_bfloat16($val);$rop = subnormalize_generic ($val, $emin, $emax, $prec);
ok so for all of these, $val can be an IV/UV, a PV, an NV, a Math::GMPf object, a Math::GMPq object, or a Math::MPFR object. literally any of them bestie, it's not picky ๐
For "float32" (aka the single precision "float"): hands you back a 24-bit precision Math::MPFR object holding the value of $val, all adjusted for either "float" subnormalization or infinitude whenever that's the move. This sub literally just calls:
subnormalize_generic($_[0], -148, 128, 24);
For "float16": hands you back an 11-bit precision Math::MPFR object with the value of $val, adjusted for either "_Float16" subnormalization or infinitude when appropriate. This one is just:
subnormalize_generic($_[0], -23, 16, 11);
For "bfloat16:: hands you back an 8-bit precision Math::MPFR object with the value of $val, adjusted for either "__bf16" subnormalization or infinitude when it applies. And yes it simply calls:
subnormalize_generic($_[0], -132, 128, 8);
For "generic": hands you back a $prec-bit precision Math::MPFR object holding $val's value, adjusted for subnormalization or infinitude (when appropriate, obvi), and it's all based on the value of $prec and the exponent range you gave it via $emin and $emax. ๐ฆ
$si = Rmpfr_get_emin();$si = Rmpfr_get_emax();
These drop the current smallest and largest exponents that are allowed for a floating-point variable into $si. ๐
$si = Rmpfr_get_emin_min();$si = Rmpfr_get_emin_max();$si = Rmpfr_get_emax_min();$si = Rmpfr_get_emax_max();
These give $si the minimum and maximum of the smallest and largest exponents allowed for 'mpfr_set_emin' and 'mpfr_set_emax'. heads up tho: these values are implementation dependent, so don't come for me if they look different on your box ๐
$bool = Rmpfr_set_emin($si);$bool = Rmpfr_set_emax($si);
Sets the smallest and largest exponents allowed for a floating-point variable. Returns a non-zero value when $si isn't inside the range of exponents your implementation accepts โ and in that case the smallest or largest exponent does not get changed โ and returns zero otherwise.
โ ๏ธ If the user changes the exponent range, it is her/his responsibility to check that all current floating-point variables are in the new allowed range (for example using 'Rmpfr_check_range'), otherwise the subsequent behaviour will be undefined, in the sense of the ISO C standard. no cap, undefined is undefined ๐ญ
$inex = Rmpfr_check_range($op, $si, $rnd);
This function assumes $op is the correctly rounded value of some real value X in the direction $rnd and some extended exponent range, and that $si is the corresponding ternary value. So $si is negative if $op is smaller than X, positive if $op is larger than X, and zero if $op equals X. ๐ง
It modifies $op if it needs to, so it lands in the current range of acceptable values. It generates an underflow or an overflow if the exponent of $op is outside the current allowed range, and the value of $si may be used to avoid a double rounding.
It returns zero if the new value of $op equals the exact one X, a positive value if that new value is larger than X, and a negative value if it's smaller than X. And note that unlike most functions, the new result $op is compared to the (unknown) exact one X, not the input value $op โ i.e., the ternary value is propagated โจ
Note: If$opis an infinity and$inexis different from zero (i.e., if the rounded result is an inexact infinity), then the overflow flag is set. ๐
Rmpfr_set_underflow();Rmpfr_set_overflow();Rmpfr_set_nanflag();Rmpfr_set_inexflag();Rmpfr_set_erangeflag();Rmpfr_set_divby0();# mpfr-3.1.0 and later onlyRmpfr_clear_underflow();Rmpfr_clear_overflow();Rmpfr_clear_nanflag();Rmpfr_clear_inexflag();Rmpfr_clear_erangeflag();Rmpfr_clear_divby0();# mpfr-3.1.0 and later only
Set/clear the underflow, overflow, invalid, inexact, erange and divide-by-zero flags. ๐ฉ
Rmpfr_clear_flags();
Clears all the global flags (underflow, overflow, inexact, invalid, erange and divide-by-zero). reset era fr fr ๐
$bool = Rmpfr_underflow_p();$bool = Rmpfr_overflow_p();$bool = Rmpfr_nanflag_p();$bool = Rmpfr_inexflag_p();$bool = Rmpfr_erangeflag_p();$bool = Rmpfr_divby0_p();# mpfr-3.1.0 and later only
Returns the corresponding (underflow, overflow, invalid, inexact, erange, divide-by-zero) flag, which is non-zero if the flag is set. the vibe check of flags tbh ๐
Rmpfr_flags_clear($mask);# needs mpfr-4.0.0 or laterRmpfr_flags_set($mask);# needs mpfr-4.0.0 or later$mask2 = Rmpfr_flags_test($mask);# needs mpfr-4.0.0 or later$mask = Rmpfr_flags_save();# needs mpfr-4.0.0 or laterRmpfr_flags_restore($mask1, $mask2);# needs mpfr-4.0.0 or later
So $mask is an integer value that you get from OR'ing (or adding) any of these constants together:
MPFR_FLAGS_UNDERFLOWMPFR_FLAGS_OVERFLOWMPFR_FLAGS_NANMPFR_FLAGS_INEXACTMPFR_FLAGS_ERANGEMPFR_FLAGS_DIVBY0MPFR_FLAGS_ALL
MPFR_FLAGS_ALL is the same as all of those constants OR'ed (added) together. Examples incoming โจ
Clear the divby0 and nan flags, without affecting the status of any other flags:
Rmpfr_flags_clear(MPFR_FLAGS_DIVBY0|MPFR_FLAGS_NAN);
Set the underflow and erange flags, without affecting the status of any other flags:
Rmpfr_flags_set(MPFR_FLAGS_UNDERFLOW|MPFR_FLAGS_ERANGE);
Test the status of specific flags, ignoring all other flags. This particular example will set $mask to the value of MPFR_FLAGS_NAN if the nan flag is set โ else $mask will be set to zero:
$mask = Rmpfr_flags_test(MPFR_FLAGS_UNDERFLOW);
Return all flags:
$mask = Rmpfr_flags_save();
Equivalently, this can be done with:
$mask = Rmpfr_flags_test(MPFR_FLAGS_ALL);
Set flags specified in $mask2 to the state specified in $mask1. For this example, the overflow flag will be set && the nan flag will be cleared. The underflow flag will remain untouched.
$mask1 = MPFR_FLAGS_UNDERFLOW | MPFR_FLAGS_OVERFLOW;
$mask2 = MPFR_FLAGS_OVERFLOW | MPFR_FLAGS_NAN;
Rmpfr_flags_restore($mask1, $mask2);
๐ MISCELLANEOUS ๐
$rop = nv2mpfr($sv);
Returns a brand new Math::MMPFR object whose value is the same as the one held by $sv, with the same precision as that of $Config{nvtype}. ๐ซถ
$str = doubletoa($double [, $x]);# Available only when# $Config{nvsize} == 8.# Else use nvtoa().
Sets $str to the value of $double.
$str will appear in standard decimal format such that the condition ($str == $double) is true.
The grisu3 algorithm used by this function, whilst very quick, will fail for about 0.5% of values. When that happens, doubletoa will (by default) fall back to using nvtoa() โ which is slower, but reliable. ๐ข
Alternatively, providing a second argument to doubletoa (any scalar will do) will ensure that it falls back to returning sprintf("%.17g", $double). This will be an accurate return, and it will be quicker than the nvtoa() fallback, but it often provides more digits than are necessary. ๐
Whenever doubletoa reverts to a fallback routine, $Math::MPFR::doubletoa_fallback (which is initially set to 0) will be incremented. This feature can be disabled by providing the FB=0 argument to the 'perl Makefile.PL' step of the Math::MPFR build.
$str = nvtoa($NV);# Available irrespective of $Config{nvsize}# and $Config{nvtype}
Sets $str to the value of $NV.
$str will appear in standard decimal format, containing the minimum number of digits such that the condition ($str == $NV) is true. โจ
NOTE 1: Except for perls whose nvtype is__float128: 1. perl versions prior to5.30.0are buggy in their assignment of values to the NV; 2. perl versions from5.30.0on that don't define$Config{d_strtod}(or respectively$Config{d_strtold}for-Duselongdoublebuilds) are also buggy in their assignment of values to the NV. Thenvtoa()function looks only at the value that was passed to it โ which, with such buggy perls, may differ from the intended value by a few ULPs. ๐ญ On these buggy perls, the bug can be avoided by assigning withatonv()โ which requiresmpfr-3.1.6or later.
NOTE 2: Be wary of values assigned by perl to double-double NVs, as such assignments may also be buggy, irrespective of the perl version. ๐ Again, with these perls, assign usingatonv()โ which requiresmpfr-3.1.6or later. With double-double NVs,nvtoa()currently requiresmpfr-4.0.0or later.
$str = mpfrtoa($op [, $uv]);# $uv is optional.
Same energy as nvtoa(), except that mpfrtoa() takes a Math::MPFR object as its argument instead.
Sets $str to the value of $op.
This is achieved by calling _mpfrtoa($op, 0).
$str will appear in standard decimal format, containing the minimum number of significant digits such that the condition ($str == $op) is true whenever the current default precision equals the precision of $op.
(The overloaded '==' operator evaluates $str according to the current default precision, so it can be that $str != $op when and only when the default precision != the precision of $op.)
The second (optional) arg became available with Math-MPFR-4.24 and it can alter the behaviour of mpfrtoa when the value of $uv is greater than the precision of $op โ which is useful in respect to subnormalization. However, if subnormal values are required use mpfrtoa_subn (documented below) instead of mpfrtoa. ๐
I have also used a 2nd argument arcanely in Math:FakeDD::dd_repro, as that seems to work. But that 2nd arg will be removed when/if I can work out how to implement that removal. (Might take a while.) ๐
$str = mpfrtoa_subn($op, $bits, $emin, $emax);
Okay so, real talk: the mpfr library does not automatically subnormalize anything for you. Which means for a given subnormal $nv, nvtoa($nv) will often come out different from mpfrtoa($op) โ even though $op == $nv ๐. Same value, different string, it's giving chaos.
This function gets its result by passing the appropriate first and second arguments to the _mpfrtoa XSub. And good news: it also works correctly with normal NV values. ๐ซถ
Some examples for those perls whose $Config{nvsize} is 8:
use Math::MPFR qw(:mpfr);
Rmpfr_set_default_prec(53); # Required precision 8-byte NVs.
$nv = 2 ** -1070;
$op = Math::MPFR->new($nv);
@args = (53, -1073, 1024);
print "ok\n" if $nv == $op; # ok
print nvtoa ($nv), "\n"; # 8e-323
print mpfrtoa($op), "\n"; # 7.905050333459945e-323
print mpfrtoa_subn($op, @args), "\n\n"; # 8e-323
# Any value with an exponent < -1073 will be zero:
$op = Math::MPFR->new(2) ** -1075; # Exponent is -1074
$nv = Rmpfr_get_NV($op, MPFR_RNDN);
print nvtoa ($nv), "\n"; # 0.0
print mpfrtoa($op), "\n"; # 2.4703282292062327e-324
print mpfrtoa_subn($op, @args), "\n\n"; # 0.0
# Any value with an exponent > 1024 will be Inf:
$op = Math::MPFR->new(2) ** 1024; # Exponent is 1025
$nv = Rmpfr_get_NV($op, MPFR_RNDN);
print nvtoa ($nv), "\n"; # Inf
print mpfrtoa($op), "\n"; # 1.797693134862316e+308
print mpfrtoa_subn($op, @args), "\n\n"; # Inf
__END__
For perls whose $Config{nvtype} is the 80-bit extended precision long double, the default precision would be set to 64 and @args to (64, -16444, 16384).
For all other perls, the default precision would be set to 113, and @args set to (113, -16493, 16384).
$str = anytoa($op);โ$opprecision must be53or64or113.
Note: it's probably now better to use mpfrtoa_subn (above) as that sub also handles subnormals and Infs. ๐
So like, if you wanna know what nvtoa(sqrt 3) would return on a perl whose nvtype is the 113-bit precision __float128 (or IEEE-754 128-bit long double) but you simply don't have access to such a perl โ no worries, bestie, you can just do this:
my $bits = 113;
Rmpfr_set_default_prec($bits);
$op = sqrt(Math::MPFR->new('3'));
my $s = anytoa($op);
print "$s\n"; # 1.7320508075688772935274463415058723
Similarly, changing $bits to 53, or 64 would provide the same as nvtoa(sqrt 3) for (respectively) the 53-bit precision double nvtype and the 64-bit extended precision long double nvtype. ๐
The value returned will be the same as returned by mpfrtoa($op) unless:
$opholds a finite value that is of such magnitude that it will become (+ or -) Inf when converted to the specified nvtype;
or
$opholds a finite non-zero value that is so close to zero that the specified nvtype will either round it to zero or denormalize it;
$mask = nvtoa_test($str, $arg [, $debug]);
DEPRECATED โ dragon_test (see below) is the recommended one instead, fr.
If $arg is a Math::MPFR object, then $str must be the string returned by mpfrtoa($arg). Else it must be the string returned by nvtoa($arg).
Otherwise, nvtoa_test is essentially the same as dragon_test. So if you want to back yourself to provide the appropriate $str/$arg combination, then please feel free to keep using nvtoa_test until such time as it is removed. ๐ญ
$mask = dragon_test($arg [, $debug]);
If $debug is provided and matches /debug/i, then some debug info is output during the running of this function. ๐
$arg can be either an IV or an NV or a Math::MPFR object.
For an IV or NV we test the string returned by nvtoa($arg) for correctness.
For a Math::MPFR object we test the string returned by mpfrtoa($arg) for correctness.
In both cases we establish that the string will assign to $arg, and that the mantissa portion of the string also contains the minimum number of significant decimal digits required for that round trip to succeed. Periodt.
$mask is initially set to zero. Then here's the whole vibe check:
- If the string assigns to
$arg(as it should) then$maskis set to1. - Also, we chop the least significant digit off the mantissa portion of the string, and add
2to$maskif this chopped string assigns to a value less than$arg. - Then we increment the least significant mantissa digit of this chopped string โ and add
4to$maskif this chopped-and-incremented string assigns to a value greater than$arg. - Also, we check that the mantissa portion of
$strcontains no unwelcome trailing zeroes โ and add8to$maskif this check passes.
$mask is then returned. If all is correct, its value will be 15. โจ
If the value of the returned $mask is not 15, then we can determine which part(s) of the test failed by examining $mask's 4 lowest bits. In the event of a failure, re-running the test with 'debug' will provide some clarifying info.
For inf, nan, and single-digit mantissas, we do only the initial test and return 15 if that test has passed, or 0 if that test has failed. (The other 3 tests don't really apply to these cases.)
$str = numtoa($sv);
As for nvtoa() but prints out UVs and IVs in integer format. (If UV-precision is greater than NV-precision then nvtoa() output can lose precision as it prints out UVs and IVs in floating point format.) ๐
$double = atodouble($str);โ needs mpfr-3.1.6 or later
Sets $double to the value of the double that's represented by the string $str.
If $Config{nvtype} is double, it therefore returns the same value as atonv. See atonv() below.
$NV = atonv($str);โ needs mpfr-3.1.6 or later
Sets $NV to the NV value represented by the string $str.
- If
$strexpresses a base 2 value, begin it with'0b'or'0B'. - If
$strexpresses a base 16 value, begin it with'0x'or'0X'. - If
$strexpresses a base 8 value then do not pass$strdirectly toatonv(). Instead do$NV = atonv(oct2bin($str));(See theoct2bindocumentation immediately below.)
For example:
atonv('0x0.89p5'), atonv('0x0.112@2'), atonv('17.125'),
atonv('0b0.10001001e5') and atonv(oct2bin('0.422p5')) all
return 17.125.
Any underscores included in the given argument will be treated as non-numeric (illegal) characters. ๐
$str2 = oct2num($str);
Treats $str as an octal string, and returns the equivalent base 2 expression of that string, including the '0b' identifying prefix. This enables atonv() to handle octal values.
The argument may (but does not need to) contain the 0/0o/0O identifying prefix. Use 'p' or 'P' to separate the mantissa from the exponent, and express the exponent as a base 10 integer. The value will be the mantissa multiplied by 2 raised to the power of that base 10 integer. For example:
'5p3' == 5 * (2 ** 3) == 40.
oct2bin('-5p3') will return the string '-0b101p3'.
$sv = atonum($str);โ needs mpfr-3.1.6 or later
$str is treated as a decimal (base 10) value.
Bases 2, 8, and 16 might be accommodated in the future. ๐ฎ
If $str numifies to an IV, return that IV. Else return the NV that is returned by atonv($str).
$ret = decimalize($op [, $anything]);โ the 2nd (optional) arg can be any scalar.
If no second argument is provided, return an exact base 10 string representation of the value held in $op.
Else, instead return the number of decimal digits (not counting leading zeros) contained in the significand of that "exact base 10 representation", as estimated by decimalize(). This value could be one greater than the actual number of those significand digits. ๐
If a second arg is supplied && $op is Inf or NaN or Zero, then the returned value will be zero.
NOTE: https://www.exploringbinary.com/maximum-number-of-decimal-digits-in-binary-floating-point-numbers/ explains that the maximum number of significant digits returned for a double precision value will be 767:
1074 + 1 + floor(log10(((2**53)-1) / (2**1074)) = 767
For the 80-bit extended precision long double:
16445 + 1 + floor(log10(((2**64)-1) / (2**16445)) = 11514
For IEEE-754 long double and _Float128:
16494 + 1 + floor(log10(((2**113)-1) / (2**16494)) = 11563
$bool = check_exact_decimal($str, $op);
Can be used to verify the string returned by decimalize(). ๐ต๏ธ
Return 1 if $str is an exact decimal representation of the value held in $op.
Else return 0.
$MPFR_version = Rmpfr_get_version();
Returns the version of the MPFR library (eg 4.0.2) being used by Math::MPFR. ๐
$GMP_version = Math::MPFR::gmp_v();
Returns the version of the gmp library (eg. 4.1.3) being used by the mpfr library that's being used by Math::MPFR.
The function is not exportable. ๐ซ
$ui = MPFR_VERSION;
An integer whose value is dependent upon the 'major', 'minor' and 'patchlevel' values of the MPFR library against which Math::MPFR was built.
This value is from the mpfr.h that was in use when the compilation of Math::MPFR took place. ๐ธ
$ui = MPFR_VERSION_MAJOR;
The 'x' in the 'x.y.z' of the MPFR library version.
This value is from the mpfr.h that was in use when the compilation of Math::MPFR took place.
$ui = MPFR_VERSION_MINOR;
The 'y' in the 'x.y.z' of the MPFR library version.
This value is from the mpfr.h that was in use when the compilation of Math::MPFR took place.
$ui = MPFR_VERSION_PATCHLEVEL;
The 'z' in the 'x.y.z' of the MPFR library version.
This value is from the mpfr.h that was in use when the compilation of Math::MPFR took place.
$string = MPFR_VERSION_STRING;
$string is set to the version of the MPFR library (eg 2.1.0) against which Math::MPFR was built.
This value is from the mpfr.h that was in use when the compilation of Math::MPFR took place. โญ
$ui = MPFR_VERSION_NUM($major, $minor, $patchlevel);
Returns the value for MPFR_VERSION for "MPFR-$major.$minor.$patchlevel". ๐
$str = Rmpfr_get_patches();โ hands you back a string stuffed with the ids of the patches that got applied to the MPFR library, aka the contents of the'PATCHES'file, all separated by spaces. ๐ฉนโจ
Note: if your program was compiled against an older MPFR version and is dynamically linked with a newer MPFR library version, then the ids of the patches applied to the old (compile-time) MPFR version just aren't available. Which, honestly? Not that deep โ that info shouldn't have much interest in general. ๐
$bool = Rmpfr_buildopt_tls_p(); # mpfr-3.0.0 and later onlyโ returns a non-zero value if mpfr was compiled as thread safe using compiler-level Thread Local Storage (meaning mpfr was built with the'--enable-thread-safe'configure option). Otherwise? Zero. Simple as that. ๐งต$bool = Rmpfr_buildopt_decimal_p(); # mpfr-3.0.0 and later onlyโ non-zero if mpfr was compiled with decimal float support (that is, mpfr was built with the'--enable-decimal-float'configure option), zero otherwise. ๐ฐ$bool = Rmpfr_buildopt_float128_p(); # mpfr-4.0.0 and later onlyโ non-zero if mpfr was compiled with__float128support (that is, mpfr was built with the'--enable-decimal-float'configure option), zero otherwise. ๐ฏ$bool = Rmpfr_buildopt_gmpinternals_p(); # mpfr-3.1.0 and later onlyโ non-zero if mpfr was compiled with gmp internals (that is, mpfr was built with either'--with-gmp-build'or'--enable-gmp-internals'configure option), zero otherwise. ๐ซฃ$bool = Rmpfr_buildopt_sharedcache_p(); # mpfr-4.0.0 and later onlyโ non-zero if MPFR was compiled so that all threads share the same cache for the one MPFR constant, likempfr_const_piormpfr_const_log2(that is, MPFR was built with the--enable-shared-cacheconfigure option). Zero otherwise. Sharing is caring bestie. ๐ซถ$str = Rmpfr_buildopt_tune_case(); # mpfr-3.1.0 and later onlyโ returns a string saying which thresholds file got used at compile time. That file is normally selected from the processor type. If"make tune"has been used, then it returns"src/mparam.h". Otherwise it'll tell you which officialmparam.hfile was used. ๐
๐ rounding-to-integer era (it's giving math)
$inex = Rmpfr_rint($rop, $op, $rnd);
$inex = Rmpfr_ceil($rop, $op);
$inex = Rmpfr_floor($rop, $op);
$inex = Rmpfr_round($rop, $op);
$inex = Rmpfr_roundeven($rop, $op); # mpfr-4.0.0 and later only
$inex = Rmpfr_trunc($rop, $op);
Okay so what these do is set $rop to $op rounded to an integer. ๐
Rmpfr_ceilrounds to the next higher representable integer.Rmpfr_floorrounds to the next lower one.Rmpfr_roundrounds to the nearest representable integer, and halfway cases go away from zero.Rmpfr_roundevenrounds to the nearest representable integer, and halfway cases follow the even-rounding rule.Rmpfr_truncrounds to the representable integer towards zero.Rmpfr_rintbehaves like one of these four functions, depending on the rounding mode. iconic honestly.
And beyond its usual meaning, $inex is:
0when$opis an integer representable in$rop1or-1when$opis an integer that is not representable in$rop2or-2when$opis not an integer
$inex = Rmpfr_rint_ceil($rop, $op, $rnd);
$inex = Rmpfr_rint_floor($rop, $op, $rnd);
$inex = Rmpfr_rint_round($rop, $op, $rnd);
$inex = Rmpfr_rint_roundeven($rop, $op, $rnd); # mpfr-4.0.0 & later
$inex = Rmpfr_rint_trunc($rop, $op, $rnd);
Same mission, sets $rop to $op rounded to an integer, but the flavour depends on which one you call:
Rmpfr_rint_ceilrounds to the next higher or equal integer.Rmpfr_rint_floorrounds to the next lower or equal integer.Rmpfr_rint_roundrounds to the nearest integer, halfway cases away from zero.Rmpfr_rint_roundevenrounds to the nearest integer, halfway cases to the nearest even integer.Rmpfr_rint_truncrounds to the next integer towards zero.
And if the result isn't representable, it gets rounded in the direction $rnd. ๐
$inex = Rmpfr_frac($rop, $op, $round);
Sets $rop to the fractional part of $op, keeping the same sign as $op, rounded in the direction $round. And here's the tea: unlike in mpfr_rint, $round only affects how the exact fractional part is rounded โ not how the fractional part is generated. Big difference, don't sleep on it. ๐ธ
$inex = Rmpfr_modf ($rop1, $rop2, $op, $rnd);
Sets $rop1 to the integral part of $op and $rop2 to the fractional part of $op at the same time, rounded in the direction RND with the corresponding precision of $rop1 and $rop2. It's literally equivalent to Rmpfr_trunc($rop1, $op, $rnd) and Rmpfr_frac($rop1, $op, $rnd).
$rop1and$rop2must be different. Return0if both results are exact. โจ
๐ the quotient-remainder squad
$inex = Rmpfr_remainder($rop, $op1, $op2, $rnd);
$inex = Rmpfr_fmod($rop, $op1, $op2, $rnd);
($si2, $si) = Rmpfr_remquo ($rop, $op1, $op2, $rnd);
($si2, $si) = Rmpfr_fmodquo ($rop, $op1, $op2, $rnd); # mpfr-4.0.0 &
# later only
Sets $rop to the value of $op - N*$op2, rounded according to the direction $rnd, where N is the integer quotient of $op1 divided by $op2, defined like this:
- N is rounded toward zero for
Rmpfr_fmodandRmpfr_fmodquo. - N is rounded to the nearest integer (ties rounded to even) for
mpfr_remainderandmpfr_remquo.
Special values are handled exactly as described in Section F.9.7.1 of the ISO C99 standard:
- If
$op1is infinite or$op2is zero,$ropis NaN. ๐ญ - If
$op2is infinite and$op1is finite,$ropis$op1rounded to the precision of$rop. - If
$ropis zero, it has the sign of$op1.
The return value is the ternary value corresponding to $rop.
Additionally, Rmpfr_remquo and Rmpfr_fmodquo store the low significant bits from the quotient in $si2 (more precisely, the number of bits in a long minus one), with the sign of $op1 divided by $op2 โ except if those low bits are all zero, in which case zero is returned. ๐ซ
Heads up:$op1may be so large in magnitude relative to$op2that an exact representation of the quotient is just not practical. And fyi,Rmpfr_remainderandRmpfr_remquofunctions are useful for additive argument reduction. ๐ง
$inex = Rmpfr_fmod_ui($rop, $op1, $ui, $rnd);
Same as Rmpfr_fmod() up above, except the 3rd arg is an unsigned long int instead of a Math::MPFR object. This function was introduced in mpfr-4.2.0-dev, but it's implemented (suboptimally) in Math::MPFR built against older versions of the mpfr library. ๐
$bool = Rmpfr_integer_p($op);
Return non-zero if $op is an integer. That's it, that's the function. โ
๐ฆ next door neighbors
Rmpfr_nexttoward($op1, $op2);
If $op1 or $op2 is NaN, set $op1 to NaN. Otherwise, if $op1 is different from $op2, replace $op1 by the next floating-point number (with the precision of $op1 and the current exponent range) in the direction of $op2, if there is one โ and yes, the infinite values are seen as the smallest and largest floating-point numbers. If the result is zero, it keeps the same sign. No underflow or overflow is generated. ๐ถโ๏ธ
Rmpfr_nextabove($op1);
Equivalent to mpfr_nexttoward where $op2 is plus infinity. โฌ๏ธ
Rmpfr_nextbelow($op1);
Equivalent to mpfr_nexttoward where $op2 is minus infinity. โฌ๏ธ
๐ min & max
$inex = Rmpfr_min($rop, $op1, $op2, $round);
Set $rop to the minimum of $op1 and $op2.
- If
$op1and$op2are both NaN, then$ropis set to NaN. - If
$op1or$op2is NaN, then$ropis set to the numeric value. - If
$op1and$op2are zeros of different signs, then$ropis set to-0.
$inex = Rmpfr_max($rop, $op1, $op2, $round);
Set $rop to the maximum of $op1 and $op2.
- If
$op1and$op2are both NaN, then$ropis set to NaN. - If
$op1or$op2is NaN, then$ropis set to the numeric value. - If
$op1and$op2are zeros of different signs, then$ropis set to+0.
๐ฉ the flag system (not exported, gatekept)
$IV = Math::MPFR::nnumflag(); # not exported
Returns the value of the non-numeric flag. This flag is initialized to zero, but it gets incremented by 1 whenever a string containing non-numeric characters is passed to an mpfr function. So the value of the flag tells us how many times such strings were passed to mpfr functions. The flag can be reset to 0 by running clear_nnum(). ๐
$IV = Math::MPFR::nok_pokflag(); # not exported
Returns the value of the nok_pok flag. This flag is initialized to zero, but it gets incremented by 1 whenever a scalar that is both a float (NOK) and string (POK) is passed to new() or to an overloaded operator. So the value of the flag tells us how many times such events occurred. The flag can be reset to 0 by running clear_nok_pok(). ๐ฏ
Math::MPFR::set_nnum($IV); # not exported
Resets the global non-numeric flag to the value specified by $IV. ๐ง
Math::MPFR::set_nok_pok($IV); # not exported
Resets the nok_pok flag to the value specified by $IV. ๐ง
Math::MPFR::clear_nnum(); # not exported
Resets the global non-numeric flag to 0. (Essentially the same as running set_nnum(0).) ๐งผ
Math::MPFR::clear_nok_pok(); # not exported
Resets the nok_pok flag to 0. (Essentially the same as running set_nok_pok(0).) ๐งผ
๐ง bytes, aka peeking at byte structure
$bytes = Math::MPFR::bytes($val, $bits);
(The semantics for calling this function have changed as of Math-MPFR-4.13.) ๐ข
Okay so the rules:
$valmust either be a string (eg'1.613e-45','2.3','0x17.8') or a Math::MPFR object.$bitsmust be one of53,64,2098or113.$byteswill be set to the hex representation of$val.
And depending on $bits:
- If
$bitsis53,$byteswill display the byte structure (in hex) of the standard 8-byte double,$val. - If
$bitsis64, the structure returned will be that of$valas an extended precision 10-byte long double. - If
$bitsis2098, the structure returned will be that of$valas the 16-byte IBM doubledouble. - If
$bitsis113, the structure returned will be that of$valas the quad precision 16-byte IEEE long double (or__float128, which is identical in byte structure).
eg:
bytes('1.3', 53) returns 3ff4cccccccccccd
bytes('1.3', 64) returns 3fffa666666666666666
bytes('1.3', 2098) returns 3ff4cccccccccccdbc8999999999999a
bytes('1.3', 113) returns 3fff4ccccccccccccccccccccccccccd
If $val is a Math::MPFR object, its precision must be $bits. ๐
For many architectures and mpfr configurations, the structures for all 4 allowed values of $bits will be accessible. In some cases, however, $bits values of 64 and/or 113 might throw a fatal error โ with a diagnostic message stating that the requested byte structure is not currently available. ๐ตโ๐ซ
$str = unpack_bfloat16($arg, $rnd, [$base]);# 16-bit "bfloat"
$str = unpack_float16($arg, $rnd, [$base]); # 16-bit half prec.
$str = unpack_float32($arg, $rnd, [$base]); # 32-bit single prec.
okay so the "bfloat16" and "float16" forms are spicy โ they need mpfr-4.3.0 or later, no cap. And even then they only work if Math::MPFR was built with __bf16 and (respectively) _Float16 support. fingers crossed bestie ๐ค
The "float32" one though? That's just the plain single precision float, and it should be universally supported, periodt. ๐
$arg can be one of IV, UV, NV, PV, or a Math::MPFR object โ it's giving "any of the above" energy.
What these do: unpack $arg's value into an upper case hex string, where $arg's value has been cast (in accordance with $rnd) to a __bf16 (bfloat) or _Float16 or _Float32 type. โจ
$base is an optional little guy that tells you the base when $arg is a PV (string). If you don't pass $base, then the base of the given PV gets determined using the approach specified in the Rmpfr_strtofr() documentation, which we already went over above in the "ASSIGNMENT" section. iykyk
For example (and yes these outputs are real, go off):
print unpack_bfloat16(-2.625, MPFR_RNDN); # Outputs C028
print unpack_float16 (-2.625, MPFR_RNDN); # Outputs C140
print unpack_float32 (-2.625, MPFR_RNDN); # Outputs C0280000
$si = IOK_flag($sv); # $sv is a perl scalar variable.
$si = NOK_flag($sv);
$si = POK_flag($sv);
These three are your little flag checkers ๐
- Return
0if$sv's IOK/NOK/POK flag is unset. - Else return
1. - BUT โ plot twist โ if the IsUV flag is set, then
IOK_flag()returns2, which is telling you that both the IOK and IsUV flags are set, and that the integer value held by$svshould therefore be treated as unsigned. ๐ซถ
๐ฒ RANDOM NUMBERS ๐ฒ
Rmpfr_urandomb(@r, $state);
Every member of @r is a Math::MPFR object. $state is a reference to a gmp_randstate_t structure.
It sets each member of @r to a uniformly distributed random float in the interval 0 <= $_ < 1. ๐
Before you even think about using this function, you gotta create $state first by calling one of the 4 Rmpfr_randinit functions, and then seed $state by calling one of the 2 Rmpfr_randseed functions. The memory associated with $state gets freed automatically when $state goes out of scope. self-cleaning, we love that
Rmpfr_random2($rop, $si, $ui); # not implemented in
# mpfr-3.0.0 and later
๐จ bestie BEWARE ๐จ โ if you try to use this when Math::MPFR was built against mpfr-3.0.0 (or later), your program will straight up die, with an appropriate error message. She's not available, she said so herself.
When it is available: generate a random float of at most abs($si) limbs, with long strings of zeros and ones in the binary representation. The exponent of the number is in the interval -$ui to $ui. This one's for testing functions and algorithms, because this kind of random number has proven more likely to trigger corner-case bugs. ๐ Negative random numbers are generated when $si is negative.
$si = Rmpfr_urandom ($rop, $state, $rnd); # mpfr-3.0.0 and
# later only
Generate a uniformly distributed random float. The floating-point number $rop can be seen as if a random real number is generated according to the continuous uniform distribution on the interval [0, 1] and then rounded in the direction RND.
Same ritual as before: create $state with one of the Rmpfr_randinit functions (below), then seed $state with one of the Rmpfr_randseed functions. ๐ธ
$si = Rmpfr_grandom($rop1, $rop2, $state, $rnd);
Available only with mpfr-3.1.x. (Was deprecated in 4.0.0.) Use Rmpfr_nrandom() if Rmpfr_grandom() is unavailable. This function will croak with an appropriate message if Math::MPFR is built against an mpfr version other than 3.1.x. ๐
Generate two random floats according to a standard normal gaussian distribution. The floating-point numbers $rop1 and $rop2 can be seen as if a random real number were generated according to the standard normal gaussian distribution and then rounded in the direction $rnd.
(yes, create $state with Rmpfr_randinit, then seed with Rmpfr_randseed โ you know the drill by now ๐ง)
$si = Rmpfr_nrandom ($rop, $state, $rnd); # mpfr-4.0.0 and
# later only
Generate a random floating-point number according to a standard normal Gaussian distribution (with mean zero and variance one). The floating-point number $rop can be seen as if a random real number were generated according to the standard normal Gaussian distribution and then rounded in the direction $rnd. This function is more efficient than Rmpfr_grandom. ๐ฅ
$si = Rmpfr_erandom($rop, $state, $rnd); # mpfr-4.0.0 and
# later only
Generate one random floating-point number according to an exponential distribution, with mean one. Other characteristics are identical to Rmpfr_nrandom. โญ
$state = Rmpfr_randinit_default();
Initialise $state with a default algorithm. This is a compromise between speed and randomness, and it's the recommended one for applications with no special requirements. the safe pick, the go-to, the vanilla that slays
$state = Rmpfr_randinit_mt();
Initialize state for a Mersenne Twister algorithm. This algorithm is fast and has good randomness properties. ๐
$state = Rmpfr_randinit_lc_2exp($a, $c, $m2exp);
โ ๏ธ This function is not tested in the test suite. Use with caution โ the author often selects values here that cause Rmpf_urandomb() to behave non-randomly. ๐ญ
Initialise $state with a linear congruential algorithm:
X = ($a * X + $c) % 2 ** $m2exp
The low bits in X are not very random โ for this reason only the high half of each X is actually used. the low bits said "no thoughts head empty"
$c and $m2exp are both unsigned longs.
$a can be any one of Math::GMP, or Math::GMPz objects. Or it can be a string.
- If it's a string of hex digits it must be prefixed with either
OXorOx. - If it's a string of octal digits it must be prefixed with
'O'. - Else it's assumed to be a decimal integer.
- No other bases are allowed. ๐
$state = Rmpfr_randinit_lc_2exp_size($ui);
Initialise state as per Rmpfr_randinit_lc_2exp. The values for $a, $c and $m2exp are selected from a table, chosen so that $ui bits (or more) of each X will be used. โจ
Rmpfr_randseed($state, $seed);
$state is a reference to a gmp_randstate_t structure โ the return value of one of the Rmpfr_randinit functions. $seed is the seed. It can be any one of Math::GMP, or Math::GMPz objects. Or it can be a string of digits.
- If it's a string of hex digits it must be prefixed with either
OXorOx. - If it's a string of octal digits it must be prefixed with
'O'. - Else it's assumed to be a decimal integer.
- No other bases are allowed. ๐
Rmpfr_randseed_ui($state, $ui);
$state is a reference to a gmp_randstate_t structure (the return value of one of the Rmpfr_randinit functions). $ui is the seed. Done, simple, iconic. ๐
๐ง INTERNALS ๐ง
$bool = Rmpfr_can_round($op, $ui, $rnd1, $rnd2, $p);
Assuming $op is an approximation of an unknown number X in direction $rnd1 with error at most two to the power E(b)-$ui where E(b) is the exponent of $op, this returns 1 if you're able to round exactly X to precision $p with direction $rnd2, and 0 otherwise.
๐ซถ heads up: this function *does not modify* its arguments. She's a looker, not a toucher.
$str = Rmpfr_print_rnd_mode($rnd);
Return a string ("MPFR_RNDD", "MPFR_RNDU", "MPFR_RNDN", "MPFR_RNDZ", "MPFR_RNDA") corresponding to the rounding mode $rnd, or return undef if $rnd is an invalid rounding mode. name that rounding mode bestie ๐ฆ
$si = Rmpfr_get_exp($op);
Return to $si the exponent of $op.
๐ฌ The behavior for nan, infinity or zero is undefined. Don't do it. Fr fr.
$si = Rmpfr_set_exp($op, $si);
Set the exponent of $op if $si is in the current exponent range, and return 0 (even if $op is not a non-zero ordinary number); otherwise, return a non-zero value. ๐ธ
$si = Rmpfr_signbit ($op);
Return a non-zero value if $op has its sign bit set (i.e. if it's negative, -0, or a NaN whose representation has its sign bit set). ๐
$si2 = Rmpfr_setsign ($rop, $op, $si, $rnd);
Set the value of $rop from $op, rounded towards the given direction $rnd, then set/clear its sign bit if $si is true/false (even when $op is a NaN). โจ
$si = Rmpfr_copysign ($rop, $op1, $op2, $rnd);
Set the value of $rop from $op1, rounded towards the given direction $rnd, then set its sign bit to that of $op2 (even when $op1 or $op2 is a NaN). This function is equivalent to:
Rmpfr_setsign ($rop, $op1, Rmpfr_signbit ($op2), $rnd)'
๐ OPERATOR OVERLOADING ๐
Overloading works with numbers, strings (bases 2, 10, and 16 only โ see step '3.' below) and Math::MPFR objects. ๐ฆ
Overloaded operations are performed using the current "default rounding mode" โ which you can determine using the 'Rmpfr_get_default_rounding_mode' function, and change using the 'Rmpfr_set_default_rounding_mode' function.
โ ๏ธ Be aware: when you use overloading with a string operand, the overload subroutine converts that string operand to a Math::MPFR object with current default precision, and using the current default rounding mode. So like... your defaults are lowkey doing a lot of work here bestie. ๐
Note that any comparison using the spaceship operator ( <=> ) will return undef if either/both of the operands is a NaN. And any comparison ( < <= > >= == != <=> ) involving one or more NaNs will set the erange flag. ๐
For the purposes of the overloaded 'not', '!' and 'bool' operators, a "false" Math::MPFR object is one whose value is either 0 (including -0) or NaN.
(A "true" Math::MPFR object is, of course, simply one that is not "false".) โจ
The following operators are overloaded:
+ - * / % ** sqrt (Return object has default precision)
+= -= *= /= %= **= ++ -- (Precision remains unchanged)
< <= > >= == != <=>
! bool
abs atan2 cos sin log exp (Return object has default precision)
int (On perl 5.8+ only, NA on perl 5.6. The return object
has default precision)
"" (Interpolates the value of the Math::MPFR object to a
decimal string)
go forth and compute, bestie ๐
<<,>>,<<=,>>=โ bestie, the Math::MPFR object gets truncated to an integer value first, always ๐ . Left shifts bump the exponent up by the value of the given "left shift" argument. For right shifts, the object's value then gets altered according to the rules of integer right shifts. So for both left and right shifts, the resultant value of the object is an integer value, periodt. Negative values for the 'shift' argument are allowed btw โ in that case the shift value gets multiplied by -1 and the direction of the shift is reversed. This is consistent with perl's shifting of NVs. no cap.=โ the copy has the same precision as the copied object. that's it, that's the tea ๐ซ
NOTE: lowkey do NOT make use of the=overloading unless you genuinely understand its caveats ๐ญ. Seeperldoc overloadand read it thoroughly, including the documentation regarding 'copy constructors'. fr fr.
Furthermore, all overloaded comparisons ( < <= > >= == != <=> ) between Math::MPFR and Math::GMPz objects, or between Math::MPFR and Math::GMPq objects, are permitted โจ. Comparison operations between Math::MPFR and Math::GMP objects must be constructed such that Math::MPFR (not Math::GMP) overloading is invoked โ that order matters, don't skip it.
Some additional cross-class overloading is also allowed ๐. Let $M be a Math::MPFR object, and $G be any one of a Math::GMPz, Math::GMPq, or Math::GMP object. Then it is permissible to do:
$M + $G;
$M += $G;
$M - $G;
$M -= $G;
$M * $G;
$M *= $G;
$M / $G;
$M /= $G;
$M % $G; (Wraps the mpfr_fmod function)
$M %= $G; (Wraps the mpfr_fmod function)
$M ** $G;
$M **= $G;
YMMV if you use old versions of Math::GMPz and Math::GMPq ๐. But if you have Math-GMPz-0.63 (or later) and Math-GMPq-0.61 (or later), and $G is either a Math::GMPz or Math::GMPq object, then it is also permissible to do the following โ and heads up, all of these will overwrite the Math::GMPz/q object ($G) with the Math::MPFR object that these operations return:
$G + $M;
$G += $M;
$G - $M;
$G -= $M;
$G * $M;
$G *= $M;
$G / $M;
$G /= $M;
$G % $M; (Wraps the mpfr_fmod function)
$G %= $M; (Wraps the mpfr_fmod function)
$G ** $M;
$G **= $M;
NOTE: in cross-class overloading, a**(power) or%(mpfr_fmod) operation that involves a Math::GMPq object means the value of the Math::GMPq object is assigned to a Math::MPFR object โ using current default precision and current default rounding mode ๐. Otherwise, the argument$Gwill be evaluated to "infinite" precision. The returned (Math::MPFR object) result will have been rounded to default precision, using default rounding mode.
The following cross-class overloading is also available if version 1.40 (or later) of Math::MPC is installed ๐. $MPC denotes a Math::MPC object. IMPORTANTLY, please note that all of these operations return a Math::MPC object, and the testing of these functions is performed only by the Math::MPC test suite:
$MPC + $M; and $M + $MPC;
$MPC += $M; and $M += $MPC;
$MPC - $M; and $M - $MPC;
$MPC -= $M; and $M -= $MPC;
$MPC * $M; and $M * $MPC;
$MPC *= $M; and $M *= $MPC;
$MPC / $M; and $M / $MPC;
$MPC /= $M; and $M /= $MPC;
$MPC ** $M; and $M ** $MPC;
$MPC **= $M; and $M **= $MPC;
To determine the type and value of the second argument received by the overloading subroutines, we work through the following steps (in order), using the first value we find, or croaking if we get to step 6 ๐ง:
- If the variable is a UV then that value is used. The variable is considered to be a UV if the
IOKandIsUVflags are set. - If the variable is an IV, then that value is used. The variable is considered to be an IV if the
IOKflag is set. - If the variable is a string (ie the
POKflag is set) then the value of that string is used. If thePOKflag is set, but the string is not a valid number, the subroutine croaks with an appropriate error message ๐. If the string starts with'0b'or'0B'it is regarded as a base 2 number. If it starts with'0x'or'0X'it is regarded as a base 16 number. Otherwise it is regarded as a base 10 number. The value is then handed to a temporary Math::MPFR object that has current default precision. Any rounding required will be done in accordance with current default rounding mode. See "STRING OVERLOADING ANOMALY" (below) for an example of possible anomalies regarding string overloading ๐. - If the variable is an NV (floating point value) then that value is used. The variable is considered to be an NV if the
NOKflag is set. Note therefore, that if the variable is both an NV (NOKflag set) and PV (POKflag also set) then the string value in the PV slot will be used. This is probably, but not necessarily, what you want, and it's recommended not to pass such values to the overloaded operators ๐ โ๏ธ. - If the variable is a Math::MPFR, Math::GMPz, or Math::GMPq, or Math::GMP object then the value of that object is used. For some operations a Math::GMP object will not be accepted, in which case the operation will die with an appropriate error message. If the variable is a Math::MPC object && the version of Math::MPC >= 1.40, then the value of that object is used, with all processing being done by Math::MPC ๐.
- If none of the above is true, then the second variable is deemed to be of an invalid type. The operation croaks with an appropriate error message ๐ญ.
๐ ๏ธ UNEXPORTED UTILITY FUNCTIONS ๐ ๏ธ
These may (or may not) be useful in examining or tweaking strings that, having been allocated in perl space, are then assigned some value in an XSub such as Rmpfr_fpif_export() or Rmpfr_sprintf(). ngl they're niche but iconic โจ
$uv = _strlen($str);โ returns the length of the string$stringas assessed by C'sstrlenfunction. This can differ fromlength($str).$uv = _SvCUR($str);โ returns theCURvalue (in bytes) of$str. This will be the same aslength($str)if$stringcontains no multi-byte characters. See "SvCUR" in the perlapi documentation.$uv = _SvLEN($str);โ returns the size of the string buffer (in bytes) in the SV. See "SvLEN" in the perlapi documentation._SvCUR_set($str, $uv);โ set theCURof$strto$uvbytes. See "SvCUR_set" in the perlapi documentation.
๐จ STRING OVERLOADING ANOMALY ๐จ
An example, when $Config{ivsize} == 8, default precision <= 63, default rounding mode is either MPFR_RNDN, MPFR_RNDU or MPFR_RNDA:
my $f = Math::MPFR->new(2 ** 64); # 0x1p+64
my $i = 18446744073709551615; # 1 less than 2 ** 64
print ($f <=> $i ); # prints 1
print ($f <=> "$i"); # prints 0
If you want an integer string in an overloaded expression to be evaluated to its full (arbitrary) precision, then convert it to a Math::GMPz object first:
print ($f <=> Math::GMPz->new("$i")); # prints 1
See t/anomaly.t in the test suite for further examples ๐.
๐ FORMATTED OUTPUT ๐
NOTE: bear in mind that, if the variable to be formatted byRmpfr_printf/Rmpfr_fprintf/Rmpfr_sprintf/Rmpfr_snprintfis a normal perl string or numeric scalar (ie PV or IV or NV) then the formatting will actually be handled by the underlying gmp/mpfr C functionality, and not by the (more lenient) perl formatting functionality ๐ฌ. For example,Rmpfr_printf("%.17g", 65416)will output rubbish, whileprintf("%.17g", 65416)will output65416. But then ... why would you invokeRmpfr_printfto do something when you have perl to DWYM ?
NOTE: frankly, I don't see any point in using the 'P' (precision) specifier in a perl environment ๐. In perl, you can simply do:
$prec = Rmpfr_get_prec($obj);
print $prec;
Why would anyone want to replace that second line with (eg):
Rmpfr_printf("%Pd\n", $prec);
Nevertheless, it is currently allowable to use the 'P' specifier with Math::MPFR's formatting functions โ but there's a caveat ๐. If $Config{ivsize} is greater than the size of the mpfr library's mpfr_prec_t type && the machine architecture is big-endian, then (AFAIK) using the 'P' specifier as just demonstrated can produce incorrect output. In such a case, the example needs to be rewritten as:
Rmpfr_printf("%Pd\n", prec_cast($prec));
The Math::MPFR::Prec package (which is part of the Math::MPFR distribution) exists solely to provide this prec_cast sub. And the prec_cast sub's return value should be passed only to the 'P' type specifier. Nothing else will understand it ๐. At some point in the future, I might do a sensible thing โ and remove both Math::MPFR::Prec and perl's support of the 'P' specifier from Math::MPFR.
prec_cast($prec);โ ensures that the'P'type specifier will provide correct results โจ. I found that simply doing (eg) :
Rmpfr_printf("%Pu\n", Rmpfr_get_prec($op));
did not work correctly for all perl configurations. For portability, that line needs to be written as:
Rmpfr_printf("%Pu\n", prec_cast(Rmpfr_get_prec($op)));
I recommend that one instead does:
print Rmpfr_get_prec($op), "\n";
Rmpfr_printf($format_string, [$rnd,] $var);
This function is not like its MPFR counterpart, bestie โ it only takes 2 or 3 arguments: the format string, optionally a rounding argument, and the variable you wanna format. That's it. Which means you can only Rmpfr_printf one variable at a time. One. Singular. No squads. ๐ญ
And if you've got no variable to format at all? Just toss a 0 in as the final argument and you're golden โ like this:
Rmpfr_printf("hello world\n", 0);
NOTE: the rounding argument$rndcan be provided only if$varis aMath::MPFRobject. Do literally anything else and it's a fatal error. No take-backs.
Okay but here's a better way (imo, and also the docs' opinion) to specify the rounding arg โ just bake it into the formatting spec instead. So instead of doing:
Rmpfr_printf("%.17R*g\n", MPFR_RNDU, $op);
do:
Rmpfr_printf("%.17RUg\n", $op);
Obsessed with the efficiency honestly. ๐
Wanna know all the formatting options? Go check the mpfr docs, they're right here: http://www.mpfr.org/mpfr-current/mpfr.html#Formatted-Output-Functions
Rmpfr_fprintf($fh, $format_string, [$rnd,] $var);
Again, not the MPFR version โ this one's limited to 3 or 4 arguments: the filehandle, the format string, optionally a rounding argument, and the variable to format. So yeah, Rmpfr_fprintf is also strictly one variable at a time. Solo performer. ๐
No variable to format? Same deal, slap a 0 on the end:
Rmpfr_fprintf($fh, "hello world\n", 0);
NOTE: the rounding argument$rndcan be provided only if$varis aMath::MPFRobject. Otherwise: fatal error. And same asRmpfr_printfup above, you can put the rounding argument in the formatting spec instead of passing it separately.
Formatting options deets live here: http://www.mpfr.org/mpfr-current/mpfr.html#Formatted-Output-Functions
Rmpfr_sprintf($buffer, $format_string, [$rnd,] $var, $buflen);
This one takes 4 or 5 arguments: the buffer (which does not have to be initialized, cute), the format string, optionally a rounding argument, the variable to format, and the size of the buffer ($buflen) where the result gets written.
$buflen must specify a size in bytes that's at least big enough to hold the formatted string, including the terminating NULL. That last bit is not optional, bestie, do not skip the NULL. ๐ค The formatted string lands in $buffer.
No variable to format? Drop a 0 in as the value for $var:
Rmpfr_sprintf($buffer, "hello world", 0, $buflen);
NOTE: the rounding argument$rndcan be provided only if$varis aMath::MPFRobject. To do otherwise is a fatal error. And as withRmpfr_printfabove, the rounding argument can go in the formatting spec instead of as its own separate argument.
Formatting details over here: http://www.mpfr.org/mpfr-current/mpfr.html#Formatted-Output-Functions
Rmpfr_snprintf($buffer, $bytes, $format_string, [$rnd,] $var, $buflen);
This one takes 5 or 6 arguments: the buffer (which ~~dowes~~ does not have to be initialized ๐
), the number of bytes to be written, the format string, optionally a rounding argument, the variable to be formatted, and the size of the buffer ($buflen).
$buflen must specify a size in bytes that's at least big enough for the formatted string, terminating NULL included. The formatted string goes into $buffer.
No variable to format? Insert a 0 as the value for $arg:
Rmpfr_snprintf($buffer, 12, "hello world", 0, $buflen);
NOTE: the rounding argument$rndcan be provided only if$varis aMath::MPFRobject. To do otherwise is a fatal error. As forRmpfr_printfabove, the rounding argument can be given in the formatting spec rather than as a separate argument.
More deets in the mpfr docs: http://www.mpfr.org/mpfr-current/mpfr.html#Formatted-Output-Functions
๐ BASE CONVERSIONS ๐
$DBL_DIG = MPFR_DBL_DIG; # Will be undef if float.h doesn't define
# DBL_DIG.
$LDBL_DIG = MPFR_LDBL_DIG; # Will be undef if float.h doesn't define
# LDBL_DIG.
$FLT128_DIG = MPFR_FLT128_DIG; # Will be undef if quadmath.h has not
# been loaded, or quadmath.h does not
# define FLT128_DIG
$min_prec = mpfr_min_inter_prec($orig_base, $orig_prec, $to_base);
NOTE:$min_preccan (very rarely) be off by one if$orig_precis in the millions, or if either$orig_baseor$to_baseare outside of the range2..64. So like, keep an eye on that. ๐
Example 1: Say we've got some base 10 integers made of 16 base 10 digits, and we wanna represent those numbers in base 2 (binary). What's the minimum required number of bits so we can guarantee that converting the base 2 representations back to base 10 gives us the original 16-digit representations?
We can calculate that minimum required precision with:
$min_prec = mpfr_min_inter_prec($orig_base, $orig_prec, $to_base);
In this example case that becomes:
$min_prec = mpfr_min_inter_prec(10, 16, 2);
which will set $min_prec to 55.
So basically: as long as our base 2 representations give at least 55 bits, we can hand them 16-digit base 10 integer values and be assured of getting the original base 10 representation back when we convert those base 2 representations back to base 10. Sureโฆ not every 16-digit value needs 55 bits, but some of them do, and none of them need more than 55 bits. Slay. โจ
Example 2:
$min_prec = mpfr_min_inter_prec(2, 53, 10);
$min_prec is set to 17.
This tells us a base 10 representation of a 53-bit integer needs to be at least 17 digits if we want to be assured that assigning that base 10 representation to a 53-bit integer gives us back a 53-bit integer identical to the original. Otherwise? No such assurance, sorry bestie. ๐ซ
$max_prec = mpfr_max_orig_prec ($orig_base, $to_base, $to_prec);
NOTE:$max_preccan (very rarely) be off by one if$to_precis in the millions, or if either$orig_baseor$to_baseare outside of the range2..64.
For example, to determine the maximum significant number of base 10 digits that can be specified when assigning to a 53-bit double, we have:
$max_len = mpfr_max_orig_len($orig_base, $to_base, $to_prec);
For this example that becomes:
$max_len = mpfr_max_orig_len(10, 2, 53);
which will set $max_len to 15.
That is, as long as our base 10 integer consists of no more than 15 significant digits, we can assign it to a 53-bit double and be assured of retrieving the original value when converting that double back to a 15-digit base 10 representation. Otherwise โ you already know the vibe โ no such assurance.
It is to be expected that
mpfr_max_orig_len(10, 2, 53) == DBL_DIG
and
mpfr_max_orig_len(10, 2, 113) == FLT128_DIG
and
mpfr_max_orig_len(10, 2, $long_double_prec) == LDBL_DIG
(where $long_double_prec is the precision, in bits, of the C long double type โ usually either 53 or 64 or 113.)
๐ TODO ๐
Look at wrapping mpfr_mp_memory_cleanup, mp_set_memory_functions.
(tbd, not done yet, she's on the list ๐)
๐ญ BUGS ๐ญ
You can get segfaults if you pass the wrong type of argument to the functions. So if you get a segfault, the first thing to do is check that the argument types you've supplied are appropriate. That's the vibe check. Don't skip it.
๐ซถ ACKNOWLEDGEMENTS ๐ซถ
Thanks to Vincent Lefevre for providing corrections to errors and omissions, and suggesting improvements (which were duly put in place). King behaviour, honestly. ๐
๐ LICENSE ๐
This program is free software; you may redistribute it and/or modify it under the same terms as Perl itself.
Copyright 2006-2026 Sisyphus
๐ AUTHOR ๐
Sisyphus <sisyphus at(@) cpan dot (.) org>
And that's a wrap on the whole page, bestie!! ๐ You made it to the very end, which is main character energy fr fr. This was perl v5.42.3, dated 2026-08-20, and the page is MPFR(3pm) โ go forth and format some floats, you absolute icon. ๐โจ๐ฆ
๐ฆ where this page comes from
- ubuntu stonking: libmath-mpfr-perl 4.47-1build1 ยท Artistic-1.0-Perl OR GPL-1.0-or-later
- ๐ girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms