You are viewing the version of this documentation from Perl 5.14.4. View the latest version

CONTENTS

NAME

Math::BigInt - Arbitrary size integer/float math package

SYNOPSIS

  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 suppress 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($y,$mod);    # modular exponentiation (($x ** $y) % $mod)
  $x->bmodinv($mod);       # modular multiplicative inverse
  $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 multiple (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!)

  # conversion 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

DESCRIPTION

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

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 conversion 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

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.

METHODS

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 Math::BigFloat, 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 Math::BigFloat. 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

Interpret the input as an octal string and return the corresponding value. A "0" (zero) prefix is optional. A single underscore character may be placed right after the prefix, if present, or between any two digits. If the input is invalid, a NaN is returned.

from_hex()

$x = Math::BigInt->from_hex("0xcafe");	# input is hexadecimal

Interpret input as a hexadecimal string. A "0x" or "x" prefix is optional. A single underscore character may be placed right after the prefix, if present, or between any two digits. If the input is invalid, a NaN is returned.

from_bin()

$x = Math::BigInt->from_bin("0b10011");	# input is binary

Interpret the input as a binary string. A "0b" or "b" prefix is optional. A single underscore character may be placed right after the prefix, if present, or between any two digits. If the input is invalid, a NaN is returned.

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

is_one()/is_zero()/is_nan()/is_inf()

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

is_pos()/is_neg()/is_positive()/is_negative()

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

is_odd()/is_even()/is_int()

$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 sign. 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