Perl 5 version 32.0 documentation

Math::BigFloat

NAME

Math::BigFloat - Arbitrary size floating point math package

SYNOPSIS

  1. use Math::BigFloat;
  2. # Configuration methods (may be used as class methods and instance methods)
  3. Math::BigFloat->accuracy(); # get class accuracy
  4. Math::BigFloat->accuracy($n); # set class accuracy
  5. Math::BigFloat->precision(); # get class precision
  6. Math::BigFloat->precision($n); # set class precision
  7. Math::BigFloat->round_mode(); # get class rounding mode
  8. Math::BigFloat->round_mode($m); # set global round mode, must be one of
  9. # 'even', 'odd', '+inf', '-inf', 'zero',
  10. # 'trunc', or 'common'
  11. Math::BigFloat->config("lib"); # name of backend math library
  12. # Constructor methods (when the class methods below are used as instance
  13. # methods, the value is assigned the invocand)
  14. $x = Math::BigFloat->new($str); # defaults to 0
  15. $x = Math::BigFloat->new('0x123'); # from hexadecimal
  16. $x = Math::BigFloat->new('0b101'); # from binary
  17. $x = Math::BigFloat->from_hex('0xc.afep+3'); # from hex
  18. $x = Math::BigFloat->from_hex('cafe'); # ditto
  19. $x = Math::BigFloat->from_oct('1.3267p-4'); # from octal
  20. $x = Math::BigFloat->from_oct('0377'); # ditto
  21. $x = Math::BigFloat->from_bin('0b1.1001p-4'); # from binary
  22. $x = Math::BigFloat->from_bin('0101'); # ditto
  23. $x = Math::BigFloat->from_ieee754($b, "binary64"); # from IEEE-754 bytes
  24. $x = Math::BigFloat->bzero(); # create a +0
  25. $x = Math::BigFloat->bone(); # create a +1
  26. $x = Math::BigFloat->bone('-'); # create a -1
  27. $x = Math::BigFloat->binf(); # create a +inf
  28. $x = Math::BigFloat->binf('-'); # create a -inf
  29. $x = Math::BigFloat->bnan(); # create a Not-A-Number
  30. $x = Math::BigFloat->bpi(); # returns pi
  31. $y = $x->copy(); # make a copy (unlike $y = $x)
  32. $y = $x->as_int(); # return as BigInt
  33. # Boolean methods (these don't modify the invocand)
  34. $x->is_zero(); # if $x is 0
  35. $x->is_one(); # if $x is +1
  36. $x->is_one("+"); # ditto
  37. $x->is_one("-"); # if $x is -1
  38. $x->is_inf(); # if $x is +inf or -inf
  39. $x->is_inf("+"); # if $x is +inf
  40. $x->is_inf("-"); # if $x is -inf
  41. $x->is_nan(); # if $x is NaN
  42. $x->is_positive(); # if $x > 0
  43. $x->is_pos(); # ditto
  44. $x->is_negative(); # if $x < 0
  45. $x->is_neg(); # ditto
  46. $x->is_odd(); # if $x is odd
  47. $x->is_even(); # if $x is even
  48. $x->is_int(); # if $x is an integer
  49. # Comparison methods
  50. $x->bcmp($y); # compare numbers (undef, < 0, == 0, > 0)
  51. $x->bacmp($y); # compare absolutely (undef, < 0, == 0, > 0)
  52. $x->beq($y); # true if and only if $x == $y
  53. $x->bne($y); # true if and only if $x != $y
  54. $x->blt($y); # true if and only if $x < $y
  55. $x->ble($y); # true if and only if $x <= $y
  56. $x->bgt($y); # true if and only if $x > $y
  57. $x->bge($y); # true if and only if $x >= $y
  58. # Arithmetic methods
  59. $x->bneg(); # negation
  60. $x->babs(); # absolute value
  61. $x->bsgn(); # sign function (-1, 0, 1, or NaN)
  62. $x->bnorm(); # normalize (no-op)
  63. $x->binc(); # increment $x by 1
  64. $x->bdec(); # decrement $x by 1
  65. $x->badd($y); # addition (add $y to $x)
  66. $x->bsub($y); # subtraction (subtract $y from $x)
  67. $x->bmul($y); # multiplication (multiply $x by $y)
  68. $x->bmuladd($y,$z); # $x = $x * $y + $z
  69. $x->bdiv($y); # division (floored), set $x to quotient
  70. # return (quo,rem) or quo if scalar
  71. $x->btdiv($y); # division (truncated), set $x to quotient
  72. # return (quo,rem) or quo if scalar
  73. $x->bmod($y); # modulus (x % y)
  74. $x->btmod($y); # modulus (truncated)
  75. $x->bmodinv($mod); # modular multiplicative inverse
  76. $x->bmodpow($y,$mod); # modular exponentiation (($x ** $y) % $mod)
  77. $x->bpow($y); # power of arguments (x ** y)
  78. $x->blog(); # logarithm of $x to base e (Euler's number)
  79. $x->blog($base); # logarithm of $x to base $base (e.g., base 2)
  80. $x->bexp(); # calculate e ** $x where e is Euler's number
  81. $x->bnok($y); # x over y (binomial coefficient n over k)
  82. $x->bsin(); # sine
  83. $x->bcos(); # cosine
  84. $x->batan(); # inverse tangent
  85. $x->batan2($y); # two-argument inverse tangent
  86. $x->bsqrt(); # calculate square root
  87. $x->broot($y); # $y'th root of $x (e.g. $y == 3 => cubic root)
  88. $x->bfac(); # factorial of $x (1*2*3*4*..$x)
  89. $x->blsft($n); # left shift $n places in base 2
  90. $x->blsft($n,$b); # left shift $n places in base $b
  91. # returns (quo,rem) or quo (scalar context)
  92. $x->brsft($n); # right shift $n places in base 2
  93. $x->brsft($n,$b); # right shift $n places in base $b
  94. # returns (quo,rem) or quo (scalar context)
  95. # Bitwise methods
  96. $x->band($y); # bitwise and
  97. $x->bior($y); # bitwise inclusive or
  98. $x->bxor($y); # bitwise exclusive or
  99. $x->bnot(); # bitwise not (two's complement)
  100. # Rounding methods
  101. $x->round($A,$P,$mode); # round to accuracy or precision using
  102. # rounding mode $mode
  103. $x->bround($n); # accuracy: preserve $n digits
  104. $x->bfround($n); # $n > 0: round to $nth digit left of dec. point
  105. # $n < 0: round to $nth digit right of dec. point
  106. $x->bfloor(); # round towards minus infinity
  107. $x->bceil(); # round towards plus infinity
  108. $x->bint(); # round towards zero
  109. # Other mathematical methods
  110. $x->bgcd($y); # greatest common divisor
  111. $x->blcm($y); # least common multiple
  112. # Object property methods (do not modify the invocand)
  113. $x->sign(); # the sign, either +, - or NaN
  114. $x->digit($n); # the nth digit, counting from the right
  115. $x->digit(-$n); # the nth digit, counting from the left
  116. $x->length(); # return number of digits in number
  117. ($xl,$f) = $x->length(); # length of number and length of fraction
  118. # part, latter is always 0 digits long
  119. # for Math::BigInt objects
  120. $x->mantissa(); # return (signed) mantissa as BigInt
  121. $x->exponent(); # return exponent as BigInt
  122. $x->parts(); # return (mantissa,exponent) as BigInt
  123. $x->sparts(); # mantissa and exponent (as integers)
  124. $x->nparts(); # mantissa and exponent (normalised)
  125. $x->eparts(); # mantissa and exponent (engineering notation)
  126. $x->dparts(); # integer and fraction part
  127. # Conversion methods (do not modify the invocand)
  128. $x->bstr(); # decimal notation, possibly zero padded
  129. $x->bsstr(); # string in scientific notation with integers
  130. $x->bnstr(); # string in normalized notation
  131. $x->bestr(); # string in engineering notation
  132. $x->bdstr(); # string in decimal notation
  133. $x->as_hex(); # as signed hexadecimal string with prefixed 0x
  134. $x->as_bin(); # as signed binary string with prefixed 0b
  135. $x->as_oct(); # as signed octal string with prefixed 0
  136. $x->to_ieee754($format); # to bytes encoded according to IEEE 754-2008
  137. # Other conversion methods
  138. $x->numify(); # return as scalar (might overflow or underflow)

DESCRIPTION

Math::BigFloat provides support for arbitrary precision floating point. Overloading is also provided for Perl operators.

All operators (including basic math operations) are overloaded if you declare your big floating point numbers as

  1. $x = Math::BigFloat -> new('12_3.456_789_123_456_789E-2');

Operations with overloaded operators preserve the arguments, which is exactly what you expect.

Input

Input values to these routines may be any scalar number or string that looks like a number and represents a floating point number.

  • Leading and trailing whitespace is ignored.

  • Leading and trailing zeros are ignored.

  • If the string has a "0x" prefix, it is interpreted as a hexadecimal number.

  • If the string has a "0b" prefix, it is interpreted as a binary number.

  • For hexadecimal and binary numbers, the exponent must be separated from the significand (mantissa) by the letter "p" or "P", not "e" or "E" as with decimal numbers.

  • One underline is allowed between any two digits, including hexadecimal and binary digits.

  • If the string can not be interpreted, NaN is returned.

Octal numbers are typically prefixed by "0", but since leading zeros are stripped, these methods can not automatically recognize octal numbers, so use the constructor from_oct() to interpret octal strings.

Some examples of valid string input

  1. Input string Resulting value
  2. 123 123
  3. 1.23e2 123
  4. 12300e-2 123
  5. 0xcafe 51966
  6. 0b1101 13
  7. 67_538_754 67538754
  8. -4_5_6.7_8_9e+0_1_0 -4567890000000
  9. 0x1.921fb5p+1 3.14159262180328369140625e+0
  10. 0b1.1001p-4 9.765625e-2

Output

Output values are usually Math::BigFloat objects.

Boolean operators is_zero() , is_one() , is_inf() , etc. return true or false.

Comparison operators bcmp() and bacmp() ) return -1, 0, 1, or undef.

METHODS

Math::BigFloat supports all methods that Math::BigInt supports, except it calculates non-integer results when possible. Please see Math::BigInt for a full description of each method. Below are just the most important differences:

Configuration methods

  • accuracy()
    1. $x->accuracy(5); # local for $x
    2. CLASS->accuracy(5); # global for all members of CLASS
    3. # Note: This also applies to new()!
    4. $A = $x->accuracy(); # read out accuracy that affects $x
    5. $A = CLASS->accuracy(); # read out global accuracy

    Set or get the global or local accuracy, aka how many significant digits the results have. If you set a global accuracy, then this also applies to new()!

    Warning! The accuracy sticks, e.g. once you created a number under the influence of CLASS->accuracy($A) , all results from math operations with that number will also be rounded.

    In most cases, you should probably round the results explicitly using one of round() in Math::BigInt, bround() in Math::BigInt or bfround() in Math::BigInt or by passing the desired accuracy to the math operation as additional parameter:

    1. my $x = Math::BigInt->new(30000);
    2. my $y = Math::BigInt->new(7);
    3. print scalar $x->copy()->bdiv($y, 2); # print 4300
    4. print scalar $x->copy()->bdiv($y)->bround(2); # print 4300
  • precision()
    1. $x->precision(-2); # local for $x, round at the second
    2. # digit right of the dot
    3. $x->precision(2); # ditto, round at the second digit
    4. # left of the dot
    5. CLASS->precision(5); # Global for all members of CLASS
    6. # This also applies to new()!
    7. CLASS->precision(-5); # ditto
    8. $P = CLASS->precision(); # read out global precision
    9. $P = $x->precision(); # read out precision that affects $x

    Note: You probably want to use accuracy() instead. With accuracy() you set the number of digits each result should have, with precision() you set the place where to round!

Constructor methods

  • from_hex()
    1. $x -> from_hex("0x1.921fb54442d18p+1");
    2. $x = Math::BigFloat -> from_hex("0x1.921fb54442d18p+1");

    Interpret input as a hexadecimal string.A prefix ("0x", "x", ignoring case) is optional. A single underscore character ("_") may be placed between any two digits. If the input is invalid, a NaN is returned. The exponent is in base 2 using decimal digits.

    If called as an instance method, the value is assigned to the invocand.

  • from_oct()
    1. $x -> from_oct("1.3267p-4");
    2. $x = Math::BigFloat -> from_oct("1.3267p-4");

    Interpret input as an octal string. A single underscore character ("_") may be placed between any two digits. If the input is invalid, a NaN is returned. The exponent is in base 2 using decimal digits.

    If called as an instance method, the value is assigned to the invocand.

  • from_bin()
    1. $x -> from_bin("0b1.1001p-4");
    2. $x = Math::BigFloat -> from_bin("0b1.1001p-4");

    Interpret input as a hexadecimal string. A prefix ("0b" or "b", ignoring case) is optional. A single underscore character ("_") may be placed between any two digits. If the input is invalid, a NaN is returned. The exponent is in base 2 using decimal digits.

    If called as an instance method, the value is assigned to the invocand.

  • from_ieee754()

    Interpret the input as a value encoded as described in IEEE754-2008. The input can be given as a byte string, hex string or binary string. The input is assumed to be in big-endian byte-order.

    1. # both $dbl and $mbf are 3.141592...
    2. $bytes = "\x40\x09\x21\xfb\x54\x44\x2d\x18";
    3. $dbl = unpack "d>", $bytes;
    4. $mbf = Math::BigFloat -> from_ieee754($bytes, "binary64");
  • bpi()
    1. print Math::BigFloat->bpi(100), "\n";

    Calculate PI to N digits (including the 3 before the dot). The result is rounded according to the current rounding mode, which defaults to "even".

    This method was added in v1.87 of Math::BigInt (June 2007).

Arithmetic methods

  • bmuladd()
    1. $x->bmuladd($y,$z);

    Multiply $x by $y, and then add $z to the result.

    This method was added in v1.87 of Math::BigInt (June 2007).

  • bdiv()
    1. $q = $x->bdiv($y);
    2. ($q, $r) = $x->bdiv($y);

    In scalar context, divides $x by $y and returns the result to the given or default accuracy/precision. In list context, does floored division (F-division), returning an integer $q and a remainder $r so that $x = $q * $y + $r. The remainer (modulo) is equal to what is returned by $x->bmod($y) .

  • bmod()
    1. $x->bmod($y);

    Returns $x modulo $y. When $x is finite, and $y is finite and non-zero, the result is identical to the remainder after floored division (F-division). If, in addition, both $x and $y are integers, the result is identical to the result from Perl's % operator.

  • bexp()
    1. $x->bexp($accuracy); # calculate e ** X

    Calculates the expression e ** $x where e is Euler's number.

    This method was added in v1.82 of Math::BigInt (April 2007).

  • bnok()
    1. $x->bnok($y); # x over y (binomial coefficient n over k)

    Calculates the binomial coefficient n over k, also called the "choose" function. The result is equivalent to:

    1. ( n ) n!
    2. | - | = -------
    3. ( k ) k!(n-k)!

    This method was added in v1.84 of Math::BigInt (April 2007).

  • bsin()
    1. my $x = Math::BigFloat->new(1);
    2. print $x->bsin(100), "\n";

    Calculate the sinus of $x, modifying $x in place.

    This method was added in v1.87 of Math::BigInt (June 2007).

  • bcos()
    1. my $x = Math::BigFloat->new(1);
    2. print $x->bcos(100), "\n";

    Calculate the cosinus of $x, modifying $x in place.

    This method was added in v1.87 of Math::BigInt (June 2007).

  • batan()
    1. my $x = Math::BigFloat->new(1);
    2. print $x->batan(100), "\n";

    Calculate the arcus tanges of $x, modifying $x in place. See also batan2().

    This method was added in v1.87 of Math::BigInt (June 2007).

  • batan2()
    1. my $y = Math::BigFloat->new(2);
    2. my $x = Math::BigFloat->new(3);
    3. print $y->batan2($x), "\n";

    Calculate the arcus tanges of $y divided by $x , modifying $y in place. See also batan().

    This method was added in v1.87 of Math::BigInt (June 2007).

  • as_float()

    This method is called when Math::BigFloat encounters an object it doesn't know how to handle. For instance, assume $x is a Math::BigFloat, or subclass thereof, and $y is defined, but not a Math::BigFloat, or subclass thereof. If you do

    1. $x -> badd($y);

    $y needs to be converted into an object that $x can deal with. This is done by first checking if $y is something that $x might be upgraded to. If that is the case, no further attempts are made. The next is to see if $y supports the method as_float() . The method as_float() is expected to return either an object that has the same class as $x, a subclass thereof, or a string that ref($x)->new() can parse to create an object.

    In Math::BigFloat, as_float() has the same effect as copy() .

  • to_ieee754()

    Encodes the invocand as a byte string in the given format as specified in IEEE 754-2008. Note that the encoded value is the nearest possible representation of the value. This value might not be exactly the same as the value in the invocand.

    1. # $x = 3.1415926535897932385
    2. $x = Math::BigFloat -> bpi(30);
    3. $b = $x -> to_ieee754("binary64"); # encode as 8 bytes
    4. $h = unpack "H*", $b; # "400921fb54442d18"
    5. # 3.141592653589793115997963...
    6. $y = Math::BigFloat -> from_ieee754($h, "binary64");

    All binary formats in IEEE 754-2008 are accepted. For convenience, som aliases are recognized: "half" for "binary16", "single" for "binary32", "double" for "binary64", "quadruple" for "binary128", "octuple" for "binary256", and "sexdecuple" for "binary512".

    See also https://en.wikipedia.org/wiki/IEEE_754.

ACCURACY AND PRECISION

See also: Rounding.

Math::BigFloat supports both precision (rounding to a certain place before or after the dot) and accuracy (rounding to a certain number of digits). For a full documentation, examples and tips on these topics please see the large section about rounding in Math::BigInt.

Since things like sqrt(2) or 1 / 3 must presented with a limited accuracy lest a operation consumes all resources, each operation produces no more than the requested number of digits.

If there is no global precision or accuracy set, and the operation in question was not called with a requested precision or accuracy, and the input $x has no accuracy or precision set, then a fallback parameter will be used. For historical reasons, it is called div_scale and can be accessed via:

  1. $d = Math::BigFloat->div_scale(); # query
  2. Math::BigFloat->div_scale($n); # set to $n digits

The default value for div_scale is 40.

In case the result of one operation has more digits than specified, it is rounded. The rounding mode taken is either the default mode, or the one supplied to the operation after the scale:

  1. $x = Math::BigFloat->new(2);
  2. Math::BigFloat->accuracy(5); # 5 digits max
  3. $y = $x->copy()->bdiv(3); # gives 0.66667
  4. $y = $x->copy()->bdiv(3,6); # gives 0.666667
  5. $y = $x->copy()->bdiv(3,6,undef,'odd'); # gives 0.666667
  6. Math::BigFloat->round_mode('zero');
  7. $y = $x->copy()->bdiv(3,6); # will also give 0.666667

Note that Math::BigFloat->accuracy() and Math::BigFloat->precision() set the global variables, and thus any newly created number will be subject to the global rounding immediately. This means that in the examples above, the 3 as argument to bdiv() will also get an accuracy of 5.

It is less confusing to either calculate the result fully, and afterwards round it explicitly, or use the additional parameters to the math functions like so:

  1. use Math::BigFloat;
  2. $x = Math::BigFloat->new(2);
  3. $y = $x->copy()->bdiv(3);
  4. print $y->bround(5),"\n"; # gives 0.66667
  5. or
  6. use Math::BigFloat;
  7. $x = Math::BigFloat->new(2);
  8. $y = $x->copy()->bdiv(3,5); # gives 0.66667
  9. print "$y\n";

Rounding

  • bfround ( +$scale )

    Rounds to the $scale'th place left from the '.', counting from the dot. The first digit is numbered 1.

  • bfround ( -$scale )

    Rounds to the $scale'th place right from the '.', counting from the dot.

  • bfround ( 0 )

    Rounds to an integer.

  • bround ( +$scale )

    Preserves accuracy to $scale digits from the left (aka significant digits) and pads the rest with zeros. If the number is between 1 and -1, the significant digits count from the first non-zero after the '.'

  • bround ( -$scale ) and bround ( 0 )

    These are effectively no-ops.

All rounding functions take as a second parameter a rounding mode from one of the following: 'even', 'odd', '+inf', '-inf', 'zero', 'trunc' or 'common'.

The default rounding mode is 'even'. By using Math::BigFloat->round_mode($round_mode); you can get and set the default mode for subsequent rounding. The usage of $Math::BigFloat::$round_mode is no longer supported. The second parameter to the round functions then overrides the default temporarily.

The as_number() function returns a BigInt from a Math::BigFloat. It uses 'trunc' as rounding mode to make it equivalent to:

  1. $x = 2.5;
  2. $y = int($x) + 2;

You can override this by passing the desired rounding mode as parameter to as_number() :

  1. $x = Math::BigFloat->new(2.5);
  2. $y = $x->as_number('odd'); # $y = 3

Autocreating constants

After use Math::BigFloat ':constant' all the floating point constants in the given scope are converted to Math::BigFloat . This conversion happens at compile time.

In particular

  1. perl -MMath::BigFloat=:constant -e 'print 2E-100,"\n"'

prints the value of 2E-100 . Note that without conversion of constants the expression 2E-100 will be calculated as normal floating point number.

Please note that ':constant' does not affect integer constants, nor binary nor hexadecimal constants. Use bignum or Math::BigInt to get this to work.

Math library

Math with the numbers is done (by default) by a module called Math::BigInt::Calc. This is equivalent to saying:

  1. use Math::BigFloat lib => 'Calc';

You can change this by using:

  1. use Math::BigFloat lib => 'GMP';

Note: General purpose packages should not be explicit about the library to use; let the script author decide which is best.

Note: The keyword 'lib' will warn when the requested library could not be loaded. To suppress the warning use 'try' instead:

  1. use Math::BigFloat try => 'GMP';

If your script works with huge numbers and Calc is too slow for them, you can also for the loading of one of these libraries and if none of them can be used, the code will die:

  1. use Math::BigFloat only => 'GMP,Pari';

The following would first try to find Math::BigInt::Foo, then Math::BigInt::Bar, and when this also fails, revert to Math::BigInt::Calc:

  1. use Math::BigFloat lib => 'Foo,Math::BigInt::Bar';

See the respective low-level library documentation for further details.

Please note that Math::BigFloat does not use the denoted library itself, but it merely passes the lib argument to Math::BigInt. So, instead of the need to do:

  1. use Math::BigInt lib => 'GMP';
  2. use Math::BigFloat;

you can roll it all into one line:

  1. use Math::BigFloat lib => 'GMP';

It is also possible to just require Math::BigFloat:

  1. require Math::BigFloat;

This will load the necessary things (like BigInt) when they are needed, and automatically.

See Math::BigInt for more details than you ever wanted to know about using a different low-level library.

Using Math::BigInt::Lite

For backwards compatibility reasons it is still possible to request a different storage class for use with Math::BigFloat:

  1. use Math::BigFloat with => 'Math::BigInt::Lite';

However, this request is ignored, as the current code now uses the low-level math library for directly storing the number parts.

EXPORTS

Math::BigFloat exports nothing by default, but can export the bpi() method:

  1. use Math::BigFloat qw/bpi/;
  2. print bpi(10), "\n";

CAVEATS

Do not try to be clever to insert some operations in between switching libraries:

  1. require Math::BigFloat;
  2. my $matter = Math::BigFloat->bone() + 4; # load BigInt and Calc
  3. Math::BigFloat->import( lib => 'Pari' ); # load Pari, too
  4. my $anti_matter = Math::BigFloat->bone()+4; # now use Pari

This will create objects with numbers stored in two different backend libraries, and VERY BAD THINGS will happen when you use these together:

  1. my $flash_and_bang = $matter + $anti_matter; # Don't do this!
  • stringify, bstr()

    Both stringify and bstr() now drop the leading '+'. The old code would return '+1.23', the new returns '1.23'. See the documentation in Math::BigInt for reasoning and details.

  • brsft()

    The following will probably not print what you expect:

    1. my $c = Math::BigFloat->new('3.14159');
    2. print $c->brsft(3,10),"\n"; # prints 0.00314153.1415

    It prints both quotient and remainder, since print calls brsft() in list context. Also, $c->brsft() will modify $c, so be careful. You probably want to use

    1. print scalar $c->copy()->brsft(3,10),"\n";
    2. # or if you really want to modify $c
    3. print scalar $c->brsft(3,10),"\n";

    instead.

  • Modifying and =

    Beware of:

    1. $x = Math::BigFloat->new(5);
    2. $y = $x;

    It will not do what you think, e.g. making a copy of $x. Instead it just makes a second reference to the same object and stores it in $y. Thus anything that modifies $x will modify $y (except overloaded math operators), and vice versa. See Math::BigInt for details and how to avoid that.

  • precision() vs. accuracy()

    A common pitfall is to use precision() when you want to round a result to a certain number of digits:

    1. use Math::BigFloat;
    2. Math::BigFloat->precision(4); # does not do what you
    3. # think it does
    4. my $x = Math::BigFloat->new(12345); # rounds $x to "12000"!
    5. print "$x\n"; # print "12000"
    6. my $y = Math::BigFloat->new(3); # rounds $y to "0"!
    7. print "$y\n"; # print "0"
    8. $z = $x / $y; # 12000 / 0 => NaN!
    9. print "$z\n";
    10. print $z->precision(),"\n"; # 4

    Replacing precision() with accuracy() is probably not what you want, either:

    1. use Math::BigFloat;
    2. Math::BigFloat->accuracy(4); # enables global rounding:
    3. my $x = Math::BigFloat->new(123456); # rounded immediately
    4. # to "12350"
    5. print "$x\n"; # print "123500"
    6. my $y = Math::BigFloat->new(3); # rounded to "3
    7. print "$y\n"; # print "3"
    8. print $z = $x->copy()->bdiv($y),"\n"; # 41170
    9. print $z->accuracy(),"\n"; # 4

    What you want to use instead is:

    1. use Math::BigFloat;
    2. my $x = Math::BigFloat->new(123456); # no rounding
    3. print "$x\n"; # print "123456"
    4. my $y = Math::BigFloat->new(3); # no rounding
    5. print "$y\n"; # print "3"
    6. print $z = $x->copy()->bdiv($y,4),"\n"; # 41150
    7. print $z->accuracy(),"\n"; # undef

    In addition to computing what you expected, the last example also does not "taint" the result with an accuracy or precision setting, which would influence any further operation.

BUGS

Please report any bugs or feature requests to bug-math-bigint at rt.cpan.org , or through the web interface at https://rt.cpan.org/Ticket/Create.html?Queue=Math-BigInt (requires login). We will be notified, and then you'll automatically be notified of progress on your bug as I make changes.

SUPPORT

You can find documentation for this module with the perldoc command.

  1. perldoc Math::BigFloat

You can also look for information at:

LICENSE

This program is free software; you may redistribute it and/or modify it under the same terms as Perl itself.

SEE ALSO

Math::BigFloat and Math::BigInt as well as the backends Math::BigInt::FastCalc, Math::BigInt::GMP, and Math::BigInt::Pari.

The pragmas bignum, bigint and bigrat also might be of interest because they solve the autoupgrading/downgrading issue, at least partly.

AUTHORS

  • Mark Biggar, overloaded interface by Ilya Zakharevich, 1996-2001.

  • Completely rewritten by Tels http://bloodgate.com in 2001-2008.

  • Florian Ragwitz <flora@cpan.org>, 2010.

  • Peter John Acklam <pjacklam@online.no>, 2011-.