Perl version

Modules

  • ABCDE
  • FGHIL
  • MNOPS
  • TUX

Math::BigFloat

Perl 5 version 10.1 documentation
Recently read

Math::BigFloat

NAME

Math::BigFloat - Arbitrary size floating point math package

SYNOPSIS

  1. use Math::BigFloat;
  2. # Number creation
  3. my $x = Math::BigFloat->new($str); # defaults to 0
  4. my $y = $x->copy(); # make a true copy
  5. my $nan = Math::BigFloat->bnan(); # create a NotANumber
  6. my $zero = Math::BigFloat->bzero(); # create a +0
  7. my $inf = Math::BigFloat->binf(); # create a +inf
  8. my $inf = Math::BigFloat->binf('-'); # create a -inf
  9. my $one = Math::BigFloat->bone(); # create a +1
  10. my $mone = Math::BigFloat->bone('-'); # create a -1
  11. my $pi = Math::BigFloat->bpi(100); # PI to 100 digits
  12. # the following examples compute their result to 100 digits accuracy:
  13. my $cos = Math::BigFloat->new(1)->bcos(100); # cosinus(1)
  14. my $sin = Math::BigFloat->new(1)->bsin(100); # sinus(1)
  15. my $atan = Math::BigFloat->new(1)->batan(100); # arcus tangens(1)
  16. my $atan2 = Math::BigFloat->new( 1 )->batan2( 1 ,100); # batan(1)
  17. my $atan2 = Math::BigFloat->new( 1 )->batan2( 8 ,100); # batan(1/8)
  18. my $atan2 = Math::BigFloat->new( -2 )->batan2( 1 ,100); # batan(-2)
  19. # Testing
  20. $x->is_zero(); # true if arg is +0
  21. $x->is_nan(); # true if arg is NaN
  22. $x->is_one(); # true if arg is +1
  23. $x->is_one('-'); # true if arg is -1
  24. $x->is_odd(); # true if odd, false for even
  25. $x->is_even(); # true if even, false for odd
  26. $x->is_pos(); # true if >= 0
  27. $x->is_neg(); # true if < 0
  28. $x->is_inf(sign); # true if +inf, or -inf (default is '+')
  29. $x->bcmp($y); # compare numbers (undef,<0,=0,>0)
  30. $x->bacmp($y); # compare absolutely (undef,<0,=0,>0)
  31. $x->sign(); # return the sign, either +,- or NaN
  32. $x->digit($n); # return the nth digit, counting from right
  33. $x->digit(-$n); # return the nth digit, counting from left
  34. # The following all modify their first argument. If you want to preserve
  35. # $x, use $z = $x->copy()->bXXX($y); See under L<CAVEATS> for why this is
  36. # necessary when mixing $a = $b assignments with non-overloaded math.
  37. # set
  38. $x->bzero(); # set $i to 0
  39. $x->bnan(); # set $i to NaN
  40. $x->bone(); # set $x to +1
  41. $x->bone('-'); # set $x to -1
  42. $x->binf(); # set $x to inf
  43. $x->binf('-'); # set $x to -inf
  44. $x->bneg(); # negation
  45. $x->babs(); # absolute value
  46. $x->bnorm(); # normalize (no-op)
  47. $x->bnot(); # two's complement (bit wise not)
  48. $x->binc(); # increment x by 1
  49. $x->bdec(); # decrement x by 1
  50. $x->badd($y); # addition (add $y to $x)
  51. $x->bsub($y); # subtraction (subtract $y from $x)
  52. $x->bmul($y); # multiplication (multiply $x by $y)
  53. $x->bdiv($y); # divide, set $x to quotient
  54. # return (quo,rem) or quo if scalar
  55. $x->bmod($y); # modulus ($x % $y)
  56. $x->bpow($y); # power of arguments ($x ** $y)
  57. $x->bmodpow($exp,$mod); # modular exponentation (($num**$exp) % $mod))
  58. $x->blsft($y, $n); # left shift by $y places in base $n
  59. $x->brsft($y, $n); # right shift by $y places in base $n
  60. # returns (quo,rem) or quo if in scalar context
  61. $x->blog(); # logarithm of $x to base e (Euler's number)
  62. $x->blog($base); # logarithm of $x to base $base (f.i. 2)
  63. $x->bexp(); # calculate e ** $x where e is Euler's number
  64. $x->band($y); # bit-wise and
  65. $x->bior($y); # bit-wise inclusive or
  66. $x->bxor($y); # bit-wise exclusive or
  67. $x->bnot(); # bit-wise not (two's complement)
  68. $x->bsqrt(); # calculate square-root
  69. $x->broot($y); # $y'th root of $x (e.g. $y == 3 => cubic root)
  70. $x->bfac(); # factorial of $x (1*2*3*4*..$x)
  71. $x->bround($N); # accuracy: preserve $N digits
  72. $x->bfround($N); # precision: round to the $Nth digit
  73. $x->bfloor(); # return integer less or equal than $x
  74. $x->bceil(); # return integer greater or equal than $x
  75. # The following do not modify their arguments:
  76. bgcd(@values); # greatest common divisor
  77. blcm(@values); # lowest common multiplicator
  78. $x->bstr(); # return string
  79. $x->bsstr(); # return string in scientific notation
  80. $x->as_int(); # return $x as BigInt
  81. $x->exponent(); # return exponent as BigInt
  82. $x->mantissa(); # return mantissa as BigInt
  83. $x->parts(); # return (mantissa,exponent) as BigInt
  84. $x->length(); # number of digits (w/o sign and '.')
  85. ($l,$f) = $x->length(); # number of digits, and length of fraction
  86. $x->precision(); # return P of $x (or global, if P of $x undef)
  87. $x->precision($n); # set P of $x to $n
  88. $x->accuracy(); # return A of $x (or global, if A of $x undef)
  89. $x->accuracy($n); # set A $x to $n
  90. # these get/set the appropriate global value for all BigFloat objects
  91. Math::BigFloat->precision(); # Precision
  92. Math::BigFloat->accuracy(); # Accuracy
  93. Math::BigFloat->round_mode(); # rounding mode

DESCRIPTION

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

  1. $i = new Math::BigFloat '12_3.456_789_123_456_789E-2';

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

Canonical notation

Input to these routines are either BigFloat objects, or strings of the following four forms:

  • /^[+-]\d+$/

  • /^[+-]\d+\.\d*$/

  • /^[+-]\d+E[+-]?\d+$/

  • /^[+-]\d*\.\d+E[+-]?\d+$/

all with optional leading and trailing zeros and/or spaces. Additionally, numbers are allowed to have an underscore between any two digits.

Empty strings as well as other illegal numbers results in 'NaN'.

bnorm() on a BigFloat object is now effectively a no-op, since the numbers are always stored in normalized form. On a string, it creates a BigFloat object.

Output

Output values are BigFloat objects (normalized), except for bstr() and bsstr().

The string output will always have leading and trailing zeros stripped and drop a plus sign. bstr() will give you always the form with a decimal point, while bsstr() (s for scientific) gives you the scientific notation.

  1. Input bstr() bsstr()
  2. '-0' '0' '0E1'
  3. ' -123 123 123' '-123123123' '-123123123E0'
  4. '00.0123' '0.0123' '123E-4'
  5. '123.45E-2' '1.2345' '12345E-4'
  6. '10E+3' '10000' '1E4'

Some routines (is_odd() , is_even() , is_zero() , is_one() , is_nan() ) return true or false, while others (bcmp() , bacmp() ) return either undef, <0, 0 or >0 and are suited for sort.

Actual math is done by using the class defined with with = Class;> (which defaults to BigInts) to represent the mantissa and exponent.

The sign /^[+-]$/ is stored separately. The string 'NaN' is used to represent the result when input arguments are not numbers, as well as the result of dividing by zero.

mantissa() , exponent() and parts()

mantissa() and exponent() return the said parts of the BigFloat as BigInts such that:

  1. $m = $x->mantissa();
  2. $e = $x->exponent();
  3. $y = $m * ( 10 ** $e );
  4. print "ok\n" if $x == $y;

($m,$e) = $x->parts(); is just a shortcut giving you both of them.

A zero is represented and returned as 0E1 , not 0E0 (after Knuth).

Currently the mantissa is reduced as much as possible, favouring higher exponents over lower ones (e.g. returning 1e7 instead of 10e6 or 10000000e0). This might change in the future, so do not depend on it.

Accuracy vs. 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 gloabl 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); # will give 0.66667
  4. $y = $x->copy()->bdiv(3,6); # will give 0.666667
  5. $y = $x->copy()->bdiv(3,6,undef,'odd'); # will give 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"; # will give 0.66667
  5. or
  6. use Math::BigFloat;
  7. $x = Math::BigFloat->new(2);
  8. $y = $x->copy()->bdiv(3,5); # will give 0.66667
  9. print "$y\n";

Rounding

  • ffround ( +$scale )

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

  • ffround ( -$scale )

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

  • ffround ( 0 )

    Rounds to an integer.

  • fround ( +$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 '.'

  • fround ( -$scale ) and fround ( 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

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:

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(), bround() or bfround() 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 digit right of the dot
  2. $x->precision(2); # ditto, round at the second digit left of the dot
  3. CLASS->precision(5); # Global for all members of CLASS
  4. # This also applies to new()!
  5. CLASS->precision(-5); # ditto
  6. $P = CLASS->precision(); # read out global precision
  7. $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!

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).

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).

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).

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).

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).

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).

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).

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 libary 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";

BUGS

Please see the file BUGS in the CPAN distribution Math::BigInt for known bugs.

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.

  • bdiv

    The following will probably not print what you expect:

    1. print $c->bdiv(123.456),"\n";

    It prints both quotient and reminder since print works in list context. Also, bdiv() will modify $c, so be careful. You probably want to use

    1. print $c / 123.456,"\n";
    2. print scalar $c->bdiv(123.456),"\n"; # or if you want to modify $c

    instead.

  • 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.

  • bpow

    bpow() now modifies the first argument, unlike the old code which left it alone and only returned the result. This is to be consistent with badd() etc. The first will modify $x, the second one won't:

    1. print bpow($x,$i),"\n"; # modify $x
    2. print $x->bpow($i),"\n"; # ditto
    3. print $x ** $i,"\n"; # leave $x alone
  • 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 think it does
    3. my $x = Math::BigFloat->new(12345); # rounds $x to "12000"!
    4. print "$x\n"; # print "12000"
    5. my $y = Math::BigFloat->new(3); # rounds $y to "0"!
    6. print "$y\n"; # print "0"
    7. $z = $x / $y; # 12000 / 0 => NaN!
    8. print "$z\n";
    9. 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 to "12350"
    4. print "$x\n"; # print "123500"
    5. my $y = Math::BigFloat->new(3); # rounded to "3
    6. print "$y\n"; # print "3"
    7. print $z = $x->copy()->bdiv($y),"\n"; # 41170
    8. 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.

SEE ALSO

Math::BigInt, Math::BigRat and Math::Big as well as Math::BigInt::BitVect, Math::BigInt::Pari and Math::BigInt::GMP.

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

The package at http://search.cpan.org/~tels/Math-BigInt contains more documentation including a full version history, testcases, empty subclass files and benchmarks.

LICENSE

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

AUTHORS

Mark Biggar, overloaded interface by Ilya Zakharevich. Completely rewritten by Tels http://bloodgate.com in 2001 - 2006, and still at it in 2007.