config()accuracy()precision()brsft()new()from_oct()from_hex()from_bin()bnan()bzero()binf()bone()bcmp()bacmp()sign()digit()bneg()babs()bnorm()bnot()binc()bdec()badd()bsub()bmul()bmuladd()bdiv()bmod()bmodinv()bmodpow()bpow()blog()bexp()bnok()bpi()bcos()bsin()batan()blsft()brsft()band()bior()bxor()bnot()bsqrt()broot()bfac()round()bround()bfround()bfloor()bceil()bgcd()blcm()exponent()mantissa()parts()copy()bsstr()as_hex()as_bin()as_oct()numify()modify()div_scale()round_mode()
Math::BigInt - Arbitrary size integer/float math package
use Math::BigInt;
# or make it faster with huge numbers: install (optional) # Math::BigInt::GMP and always use (it will fall back to # pure Perl if the GMP library is not installed): # (See also the L<MATH LIBRARY> section!)
# will warn if Math::BigInt::GMP cannot be found use Math::BigInt lib => 'GMP';
# to supress the warning use this: # use Math::BigInt try => 'GMP';
# dies if GMP cannot be loaded: # use Math::BigInt only => 'GMP';
my $str = '1234567890'; my @values = (64,74,18); my $n = 1; my $sign = '-';
# Number creation my $x = Math::BigInt->new($str); # defaults to 0 my $y = $x->copy(); # make a true copy my $nan = Math::BigInt->bnan(); # create a NotANumber my $zero = Math::BigInt->bzero(); # create a +0 my $inf = Math::BigInt->binf(); # create a +inf my $inf = Math::BigInt->binf('-'); # create a -inf my $one = Math::BigInt->bone(); # create a +1 my $mone = Math::BigInt->bone('-'); # create a -1
my $pi = Math::BigInt->bpi(); # returns '3' # see Math::BigFloat::bpi()
$h = Math::BigInt->new('0x123'); # from hexadecimal $b = Math::BigInt->new('0b101'); # from binary $o = Math::BigInt->from_oct('0101'); # from octal
# Testing (don't modify their arguments) # (return true if the condition is met, otherwise false)
$x->is_zero(); # if $x is +0 $x->is_nan(); # if $x is NaN $x->is_one(); # if $x is +1 $x->is_one('-'); # if $x is -1 $x->is_odd(); # if $x is odd $x->is_even(); # if $x is even $x->is_pos(); # if $x >= 0 $x->is_neg(); # if $x < 0 $x->is_inf($sign); # if $x is +inf, or -inf (sign is default '+') $x->is_int(); # if $x is an integer (not a float)
# comparing and digit/sign extraction $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 $x->digit($n); # return the nth digit, counting from right $x->digit(-$n); # return the nth digit, counting from left
# The following all modify their first argument. If you want to preserve # $x, use $z = $x->copy()->bXXX($y); See under L<CAVEATS> for why this is # necessary when mixing $a = $b assignments with non-overloaded math.
$x->bzero(); # set $x to 0 $x->bnan(); # set $x to NaN $x->bone(); # set $x to +1 $x->bone('-'); # set $x to -1 $x->binf(); # set $x to inf $x->binf('-'); # set $x to -inf
$x->bneg(); # negation $x->babs(); # absolute value $x->bnorm(); # normalize (no-op in BigInt) $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 $x to quotient # return (quo,rem) or quo if scalar
$x->bmuladd($y,$z); # $x = $x * $y + $z
$x->bmod($y); # modulus (x % y) $x->bmodpow($exp,$mod); # modular exponentation (($num**$exp) % $mod)) $x->bmodinv($mod); # the inverse of $x in the given modulus $mod
$x->bpow($y); # power of arguments (x ** y) $x->blsft($y); # left shift in base 2 $x->brsft($y); # right shift in base 2 # returns (quo,rem) or quo if in scalar context $x->blsft($y,$n); # left shift by $y places in base $n $x->brsft($y,$n); # right shift by $y places in base $n # returns (quo,rem) or quo if in scalar context $x->band($y); # bitwise and $x->bior($y); # bitwise inclusive or $x->bxor($y); # bitwise exclusive or $x->bnot(); # bitwise not (two's complement)
$x->bsqrt(); # calculate square-root $x->broot($y); # $y'th root of $x (e.g. $y == 3 => cubic root) $x->bfac(); # factorial of $x (1*2*3*4*..$x)
$x->bnok($y); # x over y (binomial coefficient n over k)
$x->blog(); # logarithm of $x to base e (Euler's number) $x->blog($base); # logarithm of $x to base $base (f.i. 2) $x->bexp(); # calculate e ** $x where e is Euler's number $x->round($A,$P,$mode); # round to accuracy or precision using mode $mode $x->bround($n); # accuracy: preserve $n digits $x->bfround($n); # $n > 0: round $nth digits, # $n < 0: round to the $nth digit after the # dot, no-op for BigInts
# The following do not modify their arguments in BigInt (are no-ops), # but do so in BigFloat:
$x->bfloor(); # return integer less or equal than $x $x->bceil(); # return integer greater or equal than $x # The following do not modify their arguments:
# greatest common divisor (no OO style) my $gcd = Math::BigInt::bgcd(@values); # lowest common multiplicator (no OO style) my $lcm = Math::BigInt::blcm(@values); $x->length(); # return number of digits in number ($xl,$f) = $x->length(); # length of number and length of fraction part, # latter is always 0 digits long for BigInts
$x->exponent(); # return exponent as BigInt $x->mantissa(); # return (signed) mantissa as BigInt $x->parts(); # return (mantissa,exponent) as BigInt $x->copy(); # make a true copy of $x (unlike $y = $x;) $x->as_int(); # return as BigInt (in BigInt: same as copy()) $x->numify(); # return as scalar (might overflow!) # conversation to string (do not modify their argument) $x->bstr(); # normalized string (e.g. '3') $x->bsstr(); # norm. string in scientific notation (e.g. '3E0') $x->as_hex(); # as signed hexadecimal string with prefixed 0x $x->as_bin(); # as signed binary string with prefixed 0b $x->as_oct(); # as signed octal string with prefixed 0
# precision and accuracy (see section about rounding for more) $x->precision(); # return P of $x (or global, if P of $x undef) $x->precision($n); # set P of $x to $n $x->accuracy(); # return A of $x (or global, if A of $x undef) $x->accuracy($n); # set A $x to $n
# Global methods Math::BigInt->precision(); # get/set global P for all BigInt objects Math::BigInt->accuracy(); # get/set global A for all BigInt objects Math::BigInt->round_mode(); # get/set global round mode, one of # 'even', 'odd', '+inf', '-inf', 'zero', 'trunc' or 'common' Math::BigInt->config(); # return hash containing configuration
All operators (including basic math operations) are overloaded if you declare your big integers as
$i = new Math::BigInt '123_456_789_123_456_789';
Operations with overloaded operators preserve the arguments which is exactly what you expect.
Input values to these routines may be any string, that looks like a number and results in an integer, including hexadecimal and binary numbers.
Scalars holding numbers may also be passed, but note that non-integer numbers may already have lost precision due to the conversation to float. Quote your input if you want BigInt to see all the digits:
$x = Math::BigInt->new(12345678890123456789); # bad
$x = Math::BigInt->new('12345678901234567890'); # good
You can include one underscore between any two digits.
This means integer values like 1.01E2 or even 1000E-2 are also accepted. Non-integer values result in NaN.
Hexadecimal (prefixed with "0x") and binary numbers (prefixed with "0b")
are accepted, too. Please note that octal numbers are not recognized
by new(), so the following will print "123":
perl -MMath::BigInt -le 'print Math::BigInt->new("0123")'
To convert an octal number, use from_oct();
perl -MMath::BigInt -le 'print Math::BigInt->from_oct("0123")'
Currently, Math::BigInt::new() defaults to 0, while Math::BigInt::new('') results in 'NaN'. This might change in the future, so use always the following explicit forms to get a zero or NaN:
$zero = Math::BigInt->bzero();
$nan = Math::BigInt->bnan();
bnorm() on a BigInt object is now effectively a no-op, since the numbers
are always stored in normalized form. If passed a string, creates a BigInt
object from the input.
Output values are BigInt objects (normalized), except for the methods which return a string (see SYNOPSIS).
Some routines (is_odd(), is_even(), is_zero(), is_one(),
is_nan(), etc.) return true or false, while others (bcmp(), bacmp())
return either undef (if NaN is involved), <0, 0 or >0 and are suited for sort.
Each of the methods below (except config(), accuracy() and precision())
accepts three additional parameters. These arguments $A, $P and $R
are accuracy, precision and round_mode. Please see the section about
ACCURACY and PRECISION for more information.
config()
use Data::Dumper;
print Dumper ( Math::BigInt->config() );
print Math::BigInt->config()->{lib},"\n";
Returns a hash containing the configuration, e.g. the version number, lib loaded etc. The following hash keys are currently filled in with the appropriate information.
key Description
Example
============================================================
lib Name of the low-level math library
Math::BigInt::Calc
lib_version Version of low-level math library (see 'lib')
0.30
class The class name of config() you just called
Math::BigInt
upgrade To which class math operations might be upgraded
Math::BigFloat
downgrade To which class math operations might be downgraded
undef
precision Global precision
undef
accuracy Global accuracy
undef
round_mode Global round mode
even
version version number of the class you used
1.61
div_scale Fallback accuracy for div
40
trap_nan If true, traps creation of NaN via croak()
1
trap_inf If true, traps creation of +inf/-inf via croak()
1
The following values can be set by passing config() a reference to a hash:
trap_inf trap_nan
upgrade downgrade precision accuracy round_mode div_scale
Example:
$new_cfg = Math::BigInt->config( { trap_inf => 1, precision => 5 } );
accuracy()
$x->accuracy(5); # local for $x
CLASS->accuracy(5); # global for all members of CLASS
# Note: This also applies to new()!
$A = $x->accuracy(); # read out accuracy that affects $x
$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:
my $x = Math::BigInt->new(30000);
my $y = Math::BigInt->new(7);
print scalar $x->copy()->bdiv($y, 2); # print 4300
print scalar $x->copy()->bdiv($y)->bround(2); # print 4300
Please see the section about ACCURACY AND PRECISION for further details.
Value must be greater than zero. Pass an undef value to disable it:
$x->accuracy(undef);
Math::BigInt->accuracy(undef);
Returns the current accuracy. For $x-accuracy()> it will return either the
local accuracy, or if not defined, the global. This means the return value
represents the accuracy that will be in effect for $x:
$y = Math::BigInt->new(1234567); # unrounded
print Math::BigInt->accuracy(4),"\n"; # set 4, print 4
$x = Math::BigInt->new(123456); # $x will be automatically rounded!
print "$x $y\n"; # '123500 1234567'
print $x->accuracy(),"\n"; # will be 4
print $y->accuracy(),"\n"; # also 4, since global is 4
print Math::BigInt->accuracy(5),"\n"; # set to 5, print 5
print $x->accuracy(),"\n"; # still 4
print $y->accuracy(),"\n"; # 5, since global is 5
Note: Works also for subclasses like Math::BigFloat. Each class has it's own globals separated from Math::BigInt, but it is possible to subclass Math::BigInt and make the globals of the subclass aliases to the ones from Math::BigInt.
precision()
$x->precision(-2); # local for $x, round at the second digit right of the dot
$x->precision(2); # ditto, round at the second digit left of the dot
CLASS->precision(5); # Global for all members of CLASS
# This also applies to new()!
CLASS->precision(-5); # ditto
$P = CLASS->precision(); # read out global precision
$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!
precision() sets or gets the global or local precision, aka at which digit
before or after the dot to round all results. A set global precision also
applies to all newly created numbers!
In Math::BigInt, passing a negative number precision has no effect since no numbers have digits after the dot. In the Math::BigFloat manpage, it will round all results to P digits after the dot.
Please see the section about ACCURACY AND PRECISION for further details.
Pass an undef value to disable it:
$x->precision(undef);
Math::BigInt->precision(undef);
Returns the current precision. For $x-precision()> it will return either the
local precision of $x, or if not defined, the global. This means the return
value represents the prevision that will be in effect for $x:
$y = Math::BigInt->new(1234567); # unrounded
print Math::BigInt->precision(4),"\n"; # set 4, print 4
$x = Math::BigInt->new(123456); # will be automatically rounded
print $x; # print "120000"!
Note: Works also for subclasses like the Math::BigFloat manpage. Each class has its own globals separated from Math::BigInt, but it is possible to subclass Math::BigInt and make the globals of the subclass aliases to the ones from Math::BigInt.
brsft()
$x->brsft($y,$n);
Shifts $x right by $y in base $n. Default is base 2, used are usually 10 and 2, but others work, too.
Right shifting usually amounts to dividing $x by $n ** $y and truncating the result:
$x = Math::BigInt->new(10);
$x->brsft(1); # same as $x >> 1: 5
$x = Math::BigInt->new(1234);
$x->brsft(2,10); # result 12
There is one exception, and that is base 2 with negative $x:
$x = Math::BigInt->new(-5);
print $x->brsft(1);
This will print -3, not -2 (as it would if you divide -5 by 2 and truncate the result).
new()
$x = Math::BigInt->new($str,$A,$P,$R);
Creates a new BigInt object from a scalar or another BigInt object. The input is accepted as decimal, hex (with leading '0x') or binary (with leading '0b').
See Input for more info on accepted input formats.
from_oct()
$x = Math::BigInt->from_oct("0775"); # input is octal
from_hex()
$x = Math::BigInt->from_hex("0xcafe"); # input is hexadecimal
from_bin()
$x = Math::BigInt->from_oct("0x10011"); # input is binary
bnan()
$x = Math::BigInt->bnan();
Creates a new BigInt object representing NaN (Not A Number). If used on an object, it will set it to NaN:
$x->bnan();
bzero()
$x = Math::BigInt->bzero();
Creates a new BigInt object representing zero. If used on an object, it will set it to zero:
$x->bzero();
binf()
$x = Math::BigInt->binf($sign);
Creates a new BigInt object representing infinity. The optional argument is either '-' or '+', indicating whether you want infinity or minus infinity. If used on an object, it will set it to infinity:
$x->binf();
$x->binf('-');
bone()
$x = Math::BigInt->binf($sign);
Creates a new BigInt object representing one. The optional argument is either '-' or '+', indicating whether you want one or minus one. If used on an object, it will set it to one:
$x->bone(); # +1
$x->bone('-'); # -1
$x->is_zero(); # true if arg is +0
$x->is_nan(); # true if arg is NaN
$x->is_one(); # true if arg is +1
$x->is_one('-'); # true if arg is -1
$x->is_inf(); # true if +inf
$x->is_inf('-'); # true if -inf (sign is default '+')
These methods all test the BigInt for being one specific value and return true or false depending on the input. These are faster than doing something like:
if ($x == 0)
$x->is_pos(); # true if > 0
$x->is_neg(); # true if < 0
The methods return true if the argument is positive or negative, respectively.
NaN is neither positive nor negative, while +inf counts as positive, and
-inf is negative. A zero is neither positive nor negative.
These methods are only testing the sign, and not the value.
is_positive() and is_negative() are aliases to is_pos() and
is_neg(), respectively. is_positive() and is_negative() were
introduced in v1.36, while is_pos() and is_neg() were only introduced
in v1.68.
$x->is_odd(); # true if odd, false for even
$x->is_even(); # true if even, false for odd
$x->is_int(); # true if $x is an integer
The return true when the argument satisfies the condition. NaN, +inf,
-inf are not integers and are neither odd nor even.
In BigInt, all numbers except NaN, +inf and -inf are integers.
bcmp()
$x->bcmp($y);
Compares $x with $y and takes the sign into account. Returns -1, 0, 1 or undef.
bacmp()
$x->bacmp($y);
Compares $x with $y while ignoring their. Returns -1, 0, 1 or undef.
sign()
$x->sign();
Return the sign, of $x, meaning either +, -, -inf, +inf or NaN.
If you want $x to have a certain sign, use one of the following methods:
$x->babs(); # '+'
$x->babs()->bneg(); # '-'
$x->bnan(); # 'NaN'
$x->binf(); # '+inf'
$x->binf('-'); # '-inf'
digit()
$x->digit($n); # return the nth digit, counting from right
If $n is negative, returns the digit counting from left.
bneg()
$x->bneg();
Negate the number, e.g. change the sign between '+' and '-', or between '+inf' and '-inf', respectively. Does nothing for NaN or zero.
babs()
$x->babs();
Set the number to its absolute value, e.g. change the sign from '-' to '+' and from '-inf' to '+inf', respectively. Does nothing for NaN or positive numbers.
bnorm()
$x->bnorm(); # normalize (no-op)
bnot()
$x->bnot();
Two's complement (bitwise not). This is equivalent to
$x->binc()->bneg();
but faster.
binc()
$x->binc(); # increment x by 1
bdec()
$x->bdec(); # decrement x by 1
badd()
$x->badd($y); # addition (add $y to $x)
bsub()
$x->bsub($y); # subtraction (subtract $y from $x)
bmul()
$x->bmul($y); # multiplication (multiply $x by $y)
bmuladd()
$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()
$x->bdiv($y); # divide, set $x to quotient
# return (quo,rem) or quo if scalar
bmod()
$x->bmod($y); # modulus (x % y)
bmodinv()
num->bmodinv($mod); # modular inverse
Returns the inverse of $num in the given modulus $mod. 'NaN' is
returned unless $num is relatively prime to $mod, i.e. unless
bgcd($num, $mod)==1.
bmodpow()
$num->bmodpow($exp,$mod); # modular exponentation
# ($num**$exp % $mod)
Returns the value of $num taken to the power $exp in the modulus
$mod using binary exponentation. bmodpow is far superior to
writing
$num ** $exp % $mod
because it is much faster - it reduces internal variables into the modulus whenever possible, so it operates on smaller numbers.
bmodpow also supports negative exponents.
bmodpow($num, -1, $mod)
is exactly equivalent to
bmodinv($num, $mod)
bpow()
$x->bpow($y); # power of arguments (x ** y)
blog()
$x->blog($base, $accuracy); # logarithm of x to the base $base
If $base is not defined, Euler's number (e) is used:
print $x->blog(undef, 100); # log(x) to 100 digits
bexp()
$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).
See also blog().
bnok()
$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:
( n ) n!
| - | = -------
( k ) k!(n-k)!
This method was added in v1.84 of Math::BigInt (April 2007).
bpi()
print Math::BigInt->bpi(100), "\n"; # 3
Returns PI truncated to an integer, with the argument being ignored. This means
under BigInt this always returns 3.
If upgrading is in effect, returns PI, rounded to N digits with the current rounding mode:
use Math::BigFloat;
use Math::BigInt upgrade => Math::BigFloat;
print Math::BigInt->bpi(3), "\n"; # 3.14
print Math::BigInt->bpi(100), "\n"; # 3.1415....
This method was added in v1.87 of Math::BigInt (June 2007).
bcos()
my $x = Math::BigInt->new(1);
print $x->bcos(100), "\n";
Calculate the cosinus of $x, modifying $x in place.
In BigInt, unless upgrading is in effect, the result is truncated to an integer.
This method was added in v1.87 of Math::BigInt (June 2007).
bsin()
my $x = Math::BigInt->new(1);
print $x->bsin(100), "\n";
Calculate the sinus of $x, modifying $x in place.
In BigInt, unless upgrading is in effect, the result is truncated to an integer.
This method was added in v1.87 of Math::BigInt (June 2007).
my $x = Math::BigInt->new(1);
my $y = Math::BigInt->new(1);
print $y->batan2($x), "\n";
Calculate the arcus tangens of $y divided by $x, modifying $y in place.
In BigInt, unless upgrading is in effect, the result is truncated to an integer.
This method was added in v1.87 of Math::BigInt (June 2007).
batan()
my $x = Math::BigFloat->new(0.5);
print $x->batan(100), "\n";
Calculate the arcus tangens of $x, modifying $x in place.
In BigInt, unless upgrading is in effect, the result is truncated to an integer.
This method was added in v1.87 of Math::BigInt (June 2007).
blsft()
$x->blsft($y); # left shift in base 2
$x->blsft($y,$n); # left shift, in base $n (like 10)
brsft()
$x->brsft($y); # right shift in base 2
$x->brsft($y,$n); # right shift, in base $n (like 10)
band()
$x->band($y); # bitwise and
bior()
$x->bior($y); # bitwise inclusive or
bxor()
$x->bxor($y); # bitwise exclusive or
bnot()
$x->bnot(); # bitwise not (two's complement)
bsqrt()
$x->bsqrt(); # calculate square-root
broot()
$x->broot($N);
Calculates the N'th root of $x.
bfac()
$x->bfac(); # factorial of $x (1*2*3*4*..$x)
round()
$x->round($A,$P,$round_mode);
Round $x to accuracy C<$A> or precision C<$P> using the round mode
C<$round_mode>.
bround()
$x->bround($N); # accuracy: preserve $N digits
bfround()
$x->bfround($N);
If N is > 0, rounds to the Nth digit from the left. If N < 0, rounds to the Nth digit after the dot. Since BigInts are integers, the case N < 0 is a no-op for them.
Examples:
Input N Result
===================================================
123456.123456 3 123500
123456.123456 2 123450
123456.123456 -2 123456.12
123456.123456 -3 123456.123
bfloor()
$x->bfloor();
Set $x to the integer less or equal than $x. This is a no-op in BigInt, but does change $x in BigFloat.
bceil()
$x->bceil();
Set $x to the integer greater or equal than $x. This is a no-op in BigInt, but does change $x in BigFloat.
bgcd()
bgcd(@values); # greatest common divisor (no OO style)
blcm()
blcm(@values); # lowest common multiplicator (no OO style)
head2 length()
$x->length();
($xl,$fl) = $x->length();
Returns the number of digits in the decimal representation of the number. In list context, returns the length of the integer and fraction part. For BigInt's, the length of the fraction part will always be 0.
exponent()
$x->exponent();
Return the exponent of $x as BigInt.
mantissa()
$x->mantissa();
Return the signed mantissa of $x as BigInt.
parts()
$x->parts(); # return (mantissa,exponent) as BigInt
copy()
$x->copy(); # make a true copy of $x (unlike $y = $x;)
$x->as_int();
Returns $x as a BigInt (truncated towards zero). In BigInt this is the same as
copy().
as_number() is an alias to this method. as_number was introduced in
v1.22, while as_int() was only introduced in v1.68.
=head2 bstr()
$x->bstr();
Returns a normalized string representation of $x.
bsstr()
$x->bsstr(); # normalized string in scientific notation
as_hex()
$x->as_hex(); # as signed hexadecimal string with prefixed 0x
as_bin()
$x->as_bin(); # as signed binary string with prefixed 0b
as_oct()
$x->as_oct(); # as signed octal string with prefixed 0
numify()
print $x->numify();
This returns a normal Perl scalar from $x. It is used automatically whenever a scalar is needed, for instance in array index operations.
This loses precision, to avoid this use as_int() instead.
modify()
$x->modify('bpowd');
This method returns 0 if the object can be modified with the given peration, or 1 if not.
This is used for instance by the Math::BigInt::Constant manpage.
Set/get the class for downgrade/upgrade operations. Thuis is used for instance by the bignum manpage. The defaults are '', thus the following operation will create a BigInt, not a BigFloat:
my $i = Math::BigInt->new(123);
my $f = Math::BigFloat->new('123.1');
print $i + $f,"\n"; # print 246
div_scale()Set/get the number of digits for the default precision in divide operations.
round_mode()Set/get the current round mode.
Since version v1.33, Math::BigInt and Math::BigFloat have full support for accuracy and precision based rounding, both automatically after every operation, as well as manually.
This section describes the accuracy/precision handling in Math::Big* as it used to be and as it is now, complete with an explanation of all terms and abbreviations.
Not yet implemented things (but with correct description) are marked with '!', things that need to be answered are marked with '?'.
In the next paragraph follows a short description of terms used here (because these may differ from terms used by others people or documentation).
During the rest of this document, the shortcuts A (for accuracy), P (for precision), F (fallback) and R (rounding mode) will be used.
A fixed number of digits before (positive) or after (negative) the decimal point. For example, 123.45 has a precision of -2. 0 means an integer like 123 (or 120). A precision of 2 means two digits to the left of the decimal point are zero, so 123 with P = 1 becomes 120. Note that numbers with zeros before the decimal point may have different precisions, because 1200 can have p = 0, 1 or 2 (depending on what the inital value was). It could also have p < 0, when the digits after the decimal point are zero.
The string output (of floating point numbers) will be padded with zeros:
Initial value P A Result String
------------------------------------------------------------
1234.01 -3 1000 1000
1234 -2 1200 1200
1234.5 -1 1230 1230
1234.001 1 1234 1234.0
1234.01 0 1234 1234
1234.01 2 1234.01 1234.01
1234.01 5 1234.01 1234.01000
For BigInts, no padding occurs.
Number of significant digits. Leading zeros are not counted. A number may have an accuracy greater than the non-zero digits when there are zeros in it or trailing zeros. For example, 123.456 has A of 6, 10203 has 5, 123.0506 has 7, 123.450000 has 8 and 0.000123 has 3.
The string output (of floating point numbers) will be padded with zeros:
Initial value P A Result String
------------------------------------------------------------
1234.01 3 1230 1230
1234.01 6 1234.01 1234.01
1234.1 8 1234.1 1234.1000
For BigInts, no padding occurs.
When both A and P are undefined, this is used as a fallback accuracy when dividing numbers.
When rounding a number, different 'styles' or 'kinds' of rounding are possible. (Note that random rounding, as in Math::Round, is not implemented.)
truncation invariably removes all digits following the rounding place, replacing them with zeros. Thus, 987.65 rounded to tens (P=1) becomes 980, and rounded to the fourth sigdig becomes 987.6 (A=4). 123.456 rounded to the second place after the decimal point (P=-2) becomes 123.46.
All other implemented styles of rounding attempt to round to the "nearest digit." If the digit D immediately to the right of the rounding place (skipping the decimal point) is greater than 5, the number is incremented at the rounding place (possibly causing a cascade of incrementation): e.g. when rounding to units, 0.9 rounds to 1, and -19.9 rounds to -20. If D < 5, the number is similarly truncated at the rounding place: e.g. when rounding to units, 0.4 rounds to 0, and -19.4 rounds to -19.
However the results of other styles of rounding differ if the digit immediately to the right of the rounding place (skipping the decimal point) is 5 and if there are no digits, or no digits other than 0, after that 5. In such cases:
rounds the digit at the rounding place to 0, 2, 4, 6, or 8 if it is not already. E.g., when rounding to the first sigdig, 0.45 becomes 0.4, -0.55 becomes -0.6, but 0.4501 becomes 0.5.
rounds the digit at the rounding place to 1, 3, 5, 7, or 9 if it is not already. E.g., when rounding to the first sigdig, 0.45 becomes 0.5, -0.55 becomes -0.5, but 0.5501 becomes 0.6.
round to plus infinity, i.e. always round up. E.g., when rounding to the first sigdig, 0.45 becomes 0.5, -0.55 becomes -0.5, and 0.4501 also becomes 0.5.
round to minus infinity, i.e. always round down. E.g., when rounding to the first sigdig, 0.45 becomes 0.4, -0.55 becomes -0.6, but 0.4501 becomes 0.5.
round to zero, i.e. positive numbers down, negative ones up. E.g., when rounding to the first sigdig, 0.45 becomes 0.4, -0.55 becomes -0.5, but 0.4501 becomes 0.5.
round up if the digit immediately to the right of the rounding place is 5 or greater, otherwise round down. E.g., 0.15 becomes 0.2 and 0.149 becomes 0.1.
The handling of A & P in MBI/MBF (the old core code shipped with Perl versions <= 5.7.2) is like this:
* ffround($p) is able to round to $p number of digits after the decimal
point
* otherwise P is unused
* fround($a) rounds to $a significant digits * only fdiv() and fsqrt() take A as (optional) paramater + other operations simply create the same number (fneg etc), or more (fmul) of digits + rounding/truncating is only done when explicitly calling one of fround or ffround, and never for BigInt (not implemented) * fsqrt() simply hands its accuracy argument over to fdiv. * the documentation and the comment in the code indicate two different ways on how fdiv() determines the maximum number of digits it should calculate, and the actual code does yet another thing POD: max($Math::BigFloat::div_scale,length(dividend)+length(divisor)) Comment: result has at most max(scale, length(dividend), length(divisor)) digits Actual code: scale = max(scale, length(dividend)-1,length(divisor)-1); scale += length(divisor) - length(dividend); So for lx = 3, ly = 9, scale = 10, scale will actually be 16 (10+9-3). Actually, the 'difference' added to the scale is calculated from the number of "significant digits" in dividend and divisor, which is derived by looking at the length of the mantissa. Which is wrong, since it includes the + sign (oops) and actually gets 2 for '+100' and 4 for '+101'. Oops again. Thus 124/3 with div_scale=1 will get you '41.3' based on the strange assumption that 124 has 3 significant digits, while 120/7 will get you '17', not '17.1' since 120 is thought to have 2 significant digits. The rounding after the division then uses the remainder and $y to determine wether it must round up or down. ? I have no idea which is the right way. That's why I used a slightly more ? simple scheme and tweaked the few failing testcases to match it.
This is how it works now:
* You can set the A global via C<< Math::BigInt->accuracy() >> or C<< Math::BigFloat->accuracy() >> or whatever class you are using. * You can also set P globally by using C<< Math::SomeClass->precision() >> likewise. * Globals are classwide, and not inherited by subclasses. * to undefine A, use C<< Math::SomeCLass->accuracy(undef); >> * to undefine P, use C<< Math::SomeClass->precision(undef); >> * Setting C<< Math::SomeClass->accuracy() >> clears automatically C<< Math::SomeClass->precision() >>, and vice versa. * To be valid, A must be > 0, P can have any value. * If P is negative, this means round to the P'th place to the right of the decimal point; positive values mean to the left of the decimal point. P of 0 means round to integer. * to find out the current global A, use C<< Math::SomeClass->accuracy() >> * to find out the current global P, use C<< Math::SomeClass->precision() >> * use C<< $x->accuracy() >> respective C<< $x->precision() >> for the local setting of C<< $x >>. * Please note that C<< $x->accuracy() >> respective C<< $x->precision() >> return eventually defined global A or P, when C<< $x >>'s A or P is not set.
* When you create a number,