The Perl Toolchain Summit needs more sponsors. If your company depends on Perl, please support this very important event.

NAME

Math::BigFloat - Arbitrary size floating point math package

SYNOPSIS

  use Math::BigFloat;

  # Number creation     
  $x = Math::BigInt->new($str); # defaults to 0
  $nan  = Math::BigInt->bnan(); # create a NotANumber
  $zero = Math::BigInt->bzero();# create a "+0"

  # Testing
  $x->is_zero();                # return whether arg is zero or not
  $x->is_nan();                 # return whether arg is NaN or not
  $x->is_one();                 # true if arg is +1
  $x->is_one('-');              # true if arg is -1
  $x->is_odd();                 # true if odd, false for even
  $x->is_even();                # true if even, false for odd
  $x->is_positive();            # true if >= 0
  $x->is_negative();            # true if <  0
  $x->is_inf(sign)              # true if +inf or -inf (sign default '+')
  $x->bcmp($y);                 # compare numbers (undef,<0,=0,>0)
  $x->bacmp($y);                # compare absolutely (undef,<0,=0,>0)
  $x->sign();                   # return the sign, either +,- or NaN

  # The following all modify their first argument:

  # set 
  $x->bzero();                  # set $i to 0
  $x->bnan();                   # set $i to NaN

  $x->bneg();                   # negation
  $x->babs();                   # absolute value
  $x->bnorm();                  # normalize (no-op)
  $x->bnot();                   # two's complement (bit wise not)
  $x->binc();                   # increment x by 1
  $x->bdec();                   # decrement x by 1
  
  $x->badd($y);                 # addition (add $y to $x)
  $x->bsub($y);                 # subtraction (subtract $y from $x)
  $x->bmul($y);                 # multiplication (multiply $x by $y)
  $x->bdiv($y);                 # divide, set $i to quotient
                                # return (quo,rem) or quo if scalar

  $x->bmod($y);                 # modulus
  $x->bpow($y);                 # power of arguments (a**b)
  $x->blsft($y);                # left shift
  $x->brsft($y);                # right shift 
                                # return (quo,rem) or quo if scalar
  
  $x->band($y);                 # bit-wise and
  $x->bior($y);                 # bit-wise inclusive or
  $x->bxor($y);                 # bit-wise exclusive or
  $x->bnot();                   # bit-wise not (two's complement)
  
  $x->bround($N);               # accuracy: preserver $N digits
  $x->bfround($N);              # precision: round to the $Nth digit

  # The following do not modify their arguments:

  bgcd(@values);                # greatest common divisor
  blcm(@values);                # lowest common multiplicator
  
  $x->bstr();                   # return string
  $x->bsstr();                  # return string in scientific notation
  
  $x->exponent();               # return exponent as BigInt
  $x->mantissa();               # return mantissa as BigInt
  $x->parts();                  # return (mantissa,exponent) as BigInt

  $x->length();                 # number of digits (w/o sign and '.')
  ($l,$f) = $x->length();       # number of digits, and length of fraction      

DESCRIPTION

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

  $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. Additonally, 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() (for scientific) gives you the scientific notation.

        Input                   bstr()          bsstr()
        '-0'                    '0'             '0E1'
        '  -123 123 123'        '-123123123'    '-123123123E0'
        '00.0123'               '0.0123'        '123E-4'
        '123.45E-2'             '1.2345'        '12345E-4'
        '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 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:

        $m = $x->mantissa();
        $e = $x->exponent();
        $y = $m * ( 10 ** $e );
        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 and accuracy. (here should follow a short description of both).

Precision: digits after the '.', laber, schwad Accuracy: Significant digits blah blah

Since things like sqrt(2) or 1/3 must presented with a limited precision lest a operation consumes all resources, each operation produces no more than Math::BigFloat::precision() digits.

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

        $x = Math::BigFloat->new(2);
        Math::BigFloat::precision(5);           # 5 digits max
        $y = $x->copy()->bdiv(3);               # will give 0.66666
        $y = $x->copy()->bdiv(3,6);             # will give 0.666666
        $y = $x->copy()->bdiv(3,6,'odd');       # will give 0.666667
        Math::BigFloat::round_mode('zero');
        $y = $x->copy()->bdiv(3,6);             # will give 0.666666

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 effetively no-ops.

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

The default rounding mode is 'even'. By using Math::BigFloat::round_mode($rnd_mode); you can get and set the default mode for subsequent rounding. The usage of $Math::BigFloat::$rnd_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:

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

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

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

EXAMPLES

  use Math::BigFloat qw(bstr bint);
  # not ready yet
  $x = bstr("1234")                    # string "1234"
  $x = "$x";                           # same as bstr()
  $x = bneg("1234")                    # BigFloat "-1234"
  $x = Math::BigFloat->bneg("1234");   # BigFloat "1234"
  $x = Math::BigFloat->babs("-12345"); # BigFloat "12345"
  $x = Math::BigFloat->bnorm("-0 00"); # BigFloat "0"
  $x = bint(1) + bint(2);              # BigFloat "3"
  $x = bint(1) + "2";                  # ditto (auto-BigFloatify of "2")
  $x = bint(1);                        # BigFloat "1"
  $x = $x + 5 / 2;                     # BigFloat "3"
  $x = $x ** 3;                        # BigFloat "27"
  $x *= 2;                             # BigFloat "54"
  $x = new Math::BigFloat;             # BigFloat "0"
  $x--;                                # BigFloat "-1"

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

  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.

PERFORMANCE

Greatly enhanced ;o) SectionNotReadyYet.

BUGS

  • The following does not work yet:

            $m = $x->mantissa();
            $e = $x->exponent();
            $y = $m * ( 10 ** $e );
            print "ok\n" if $x == $y;
  • There is no fmod() function yet.

CAVEAT

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 do what you expect:

        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 carefull. You probably want to use

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

instead.

Modifying and =

Beware of:

        $x = Math::BigFloat->new(5);
        $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, and vice versa.

        $x->bmul(2);
        print "$x, $y\n";       # prints '10, 10'

If you want a true copy of $x, use:

        $y = $x->copy();

See also the documentation in overload regarding =.

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:

        print bpow($x,$i),"\n";         # modify $x
        print $x->bpow($i),"\n";        # ditto
        print $x ** $i,"\n";            # leave $x alone 

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.