7 @EXPORT_OK = qw( PI e bpi bexp hex oct );
8 @EXPORT = qw( inf NaN );
13 ##############################################################################
15 # These are all alike, and thus faked by AUTOLOAD
17 my @faked = qw/round_mode accuracy precision div_scale/;
18 use vars qw/$VERSION $AUTOLOAD $_lite/; # _lite for testsuite
24 $name =~ s/.*:://; # split package
26 foreach my $n (@faked)
30 *{"bigint::$name"} = sub
36 return Math::BigInt->$name($_[0]);
38 return Math::BigInt->$name();
44 # delayed load of Carp and avoid recursion
46 Carp::croak ("Can't call bigint\-\>$name, not a valid method");
51 $Math::BigInt::upgrade;
56 # this takes a binary/hexadecimal/octal constant string and returns it
57 # as string suitable for new. Basically it converts octal to decimal, and
58 # passes every thing else unmodified back.
61 return Math::BigInt->new($string) if $string =~ /^0[bx]/;
63 # so it must be an octal constant
64 Math::BigInt->from_oct($string);
69 # this takes a floating point constant string and returns it truncated to
70 # integer. For instance, '4.5' => '4', '1.234e2' => '123' etc
73 # some simple cases first
74 return $float if ($float =~ /^[+-]?[0-9]+$/); # '+123','-1','0' etc
76 if ($float =~ /^[+-]?[0-9]+\.?[eE]\+?[0-9]+$/); # 123e2, 123.e+2
77 return '0' if ($float =~ /^[+-]?[0]*\.[0-9]+$/); # .2, 0.2, -.1
78 if ($float =~ /^[+-]?[0-9]+\.[0-9]*$/) # 1., 1.23, -1.2 etc
83 my ($mis,$miv,$mfv,$es,$ev) = Math::BigInt::_split($float);
84 return $float if !defined $mis; # doesn't look like a number to me
86 my $sign = $$mis; $sign = '' if $sign eq '+';
89 # ignore fraction part entirely
90 if ($ec >= length($$miv)) # 123.23E-4
94 return $sign . substr ($$miv,0,length($$miv)-$ec); # 1234.45E-2 = 12
97 if ($ec >= length($$mfv))
100 return $sign.$$miv.$$mfv if $ec == 0; # 123.45E+2 => 12345
101 return $sign.$$miv.$$mfv.'E'.$ec; # 123.45e+3 => 12345e1
103 $mfv = substr($$mfv,0,$ec);
104 $sign.$$miv.$mfv; # 123.45e+1 => 1234
109 $^H{bigint} = undef; # no longer in effect
110 overload::remove_constant('binary','','float','','integer');
115 my $level = shift || 0;
116 my $hinthash = (caller($level))[10];
120 #############################################################################
121 # the following two routines are for "use bigint qw/hex oct/;":
123 use constant LEXICAL => $] > 5.009004;
126 my $proto = LEXICAL ? '_' : ';$';
128 sub hex(' . $proto . ')' . <<'.';
130 my $i = @_ ? $_[0] : $_;
131 $i = '0x'.$i unless $i =~ /^0x/;
132 Math::BigInt->new($i);
136 sub oct(' . $proto . ')' . <<'.';
138 my $i = @_ ? $_[0] : $_;
139 # oct() should never fall back to decimal
140 return Math::BigInt->from_oct($i) if $i =~ s/^(?=0[0-9]|[1-9])/0/;
141 Math::BigInt->new($i);
146 #############################################################################
147 # the following two routines are for Perl 5.9.4 or later and are lexical
149 my ($prev_oct, $prev_hex, $overridden);
151 if (LEXICAL) { eval <<'.' }
154 my $hh = (caller 0)[10];
155 return $prev_hex ? &$prev_hex($_[0]) : CORE::hex($_[0])
156 unless $$hh{bigint}||$$hh{bignum}||$$hh{bigrat};
158 $i = '0x'.$i unless $i =~ /^0x/;
159 Math::BigInt->new($i);
164 my $hh = (caller 0)[10];
165 return $prev_oct ? &$prev_oct($_[0]) : CORE::oct($_[0])
166 unless $$hh{bigint}||$$hh{bignum}||$$hh{bigrat};
168 # oct() should never fall back to decimal
169 return Math::BigInt->from_oct($i) if $i =~ s/^(?=0[0-9]|[1-9])/0/;
170 Math::BigInt->new($i);
176 return if $overridden;
177 $prev_oct = *CORE::GLOBAL::oct{CODE};
178 $prev_hex = *CORE::GLOBAL::hex{CODE};
179 no warnings 'redefine';
180 *CORE::GLOBAL::oct = \&_oct;
181 *CORE::GLOBAL::hex = \&_hex;
189 $^H{bigint} = 1; # we are in effect
191 # for newer Perls always override hex() and oct() with a lexical version:
197 my $lib = ''; my $lib_kind = 'try';
199 my @import = ( ':constant' ); # drive it w/ constant
200 my @a = @_; my $l = scalar @_; my $j = 0;
201 my ($ver,$trace); # version? trace?
202 my ($a,$p); # accuracy, precision
203 for ( my $i = 0; $i < $l ; $i++,$j++ )
205 if ($_[$i] =~ /^(l|lib|try|only)$/)
207 # this causes a different low lib to take care...
208 $lib_kind = $1; $lib_kind = 'lib' if $lib_kind eq 'l';
209 $lib = $_[$i+1] || '';
210 my $s = 2; $s = 1 if @a-$j < 2; # avoid "can not modify non-existent..."
211 splice @a, $j, $s; $j -= $s; $i++;
213 elsif ($_[$i] =~ /^(a|accuracy)$/)
216 my $s = 2; $s = 1 if @a-$j < 2; # avoid "can not modify non-existent..."
217 splice @a, $j, $s; $j -= $s; $i++;
219 elsif ($_[$i] =~ /^(p|precision)$/)
222 my $s = 2; $s = 1 if @a-$j < 2; # avoid "can not modify non-existent..."
223 splice @a, $j, $s; $j -= $s; $i++;
225 elsif ($_[$i] =~ /^(v|version)$/)
228 splice @a, $j, 1; $j --;
230 elsif ($_[$i] =~ /^(t|trace)$/)
233 splice @a, $j, 1; $j --;
235 elsif ($_[$i] !~ /^(PI|e|bpi|bexp|hex|oct)\z/)
237 die ("unknown option $_[$i]");
241 $_lite = 0; # using M::BI::L ?
244 require Math::BigInt::Trace; $class = 'Math::BigInt::Trace';
248 # see if we can find Math::BigInt::Lite
249 if (!defined $a && !defined $p) # rounding won't work to well
251 eval 'require Math::BigInt::Lite;';
254 @import = ( ); # :constant in Lite, not MBI
255 Math::BigInt::Lite->import( ':constant' );
256 $_lite= 1; # signal okay
259 require Math::BigInt if $_lite == 0; # not already loaded?
260 $class = 'Math::BigInt'; # regardless of MBIL or not
262 push @import, $lib_kind => $lib if $lib ne '';
263 # Math::BigInt::Trace or plain Math::BigInt
264 $class->import(@import);
266 bigint->accuracy($a) if defined $a;
267 bigint->precision($p) if defined $p;
270 print "bigint\t\t\t v$VERSION\n";
271 print "Math::BigInt::Lite\t v$Math::BigInt::Lite::VERSION\n" if $_lite;
272 print "Math::BigInt\t\t v$Math::BigInt::VERSION";
273 my $config = Math::BigInt->config();
274 print " lib => $config->{lib} v$config->{lib_version}\n";
277 # we take care of floating point constants, since BigFloat isn't available
278 # and BigInt doesn't like them:
279 overload::constant float => sub { Math::BigInt->new( _float_constant(shift) ); };
280 # Take care of octal/hexadecimal constants
281 overload::constant binary => sub { _binary_constant(shift) };
283 # if another big* was already loaded:
284 my ($package) = caller();
287 if (!defined *{"${package}::inf"})
289 $self->export_to_level(1,$self,@a); # export inf and NaN, e and PI
293 sub inf () { Math::BigInt::binf(); }
294 sub NaN () { Math::BigInt::bnan(); }
296 sub PI () { Math::BigInt->new(3); }
297 sub e () { Math::BigInt->new(2); }
298 sub bpi ($) { Math::BigInt->new(3); }
299 sub bexp ($$) { my $x = Math::BigInt->new($_[0]); $x->bexp($_[1]); }
307 bigint - Transparent BigInteger support for Perl
313 $x = 2 + 4.5,"\n"; # BigInt 6
314 print 2 ** 512,"\n"; # really is what you think it is
315 print inf + 42,"\n"; # inf
316 print NaN * 7,"\n"; # NaN
317 print hex("0x1234567890123490"),"\n"; # Perl v5.10.0 or later
321 print 2 ** 256,"\n"; # a normal Perl scalar now
324 # Import into current package:
325 use bigint qw/hex oct/;
326 print hex("0x1234567890123490"),"\n";
327 print oct("01234567890123490"),"\n";
331 All operators (including basic math operations) except the range operator C<..>
332 are overloaded. Integer constants are created as proper BigInts.
334 Floating point constants are truncated to integer. All parts and results of
335 expressions are also truncated.
337 Unlike L<integer>, this pragma creates integer constants that are only
338 limited in their size by the available memory and CPU time.
340 =head2 use integer vs. use bigint
342 There is one small difference between C<use integer> and C<use bigint>: the
343 former will not affect assignments to variables and the return value of
344 some functions. C<bigint> truncates these results to integer too:
346 # perl -Minteger -wle 'print 3.2'
348 # perl -Minteger -wle 'print 3.2 + 0'
350 # perl -Mbigint -wle 'print 3.2'
352 # perl -Mbigint -wle 'print 3.2 + 0'
355 # perl -Mbigint -wle 'print exp(1) + 0'
357 # perl -Mbigint -wle 'print exp(1)'
359 # perl -Minteger -wle 'print exp(1)'
361 # perl -Minteger -wle 'print exp(1) + 0'
364 In practice this makes seldom a difference as B<parts and results> of
365 expressions will be truncated anyway, but this can, for instance, affect the
366 return value of subroutines:
368 sub three_integer { use integer; return 3.2; }
369 sub three_bigint { use bigint; return 3.2; }
371 print three_integer(), " ", three_bigint(),"\n"; # prints "3.2 3"
375 bigint recognizes some options that can be passed while loading it via use.
376 The options can (currently) be either a single letter form, or the long form.
377 The following options exist:
383 This sets the accuracy for all math operations. The argument must be greater
384 than or equal to zero. See Math::BigInt's bround() function for details.
386 perl -Mbigint=a,2 -le 'print 12345+1'
388 Note that setting precision and accuracy at the same time is not possible.
392 This sets the precision for all math operations. The argument can be any
393 integer. Negative values mean a fixed number of digits after the dot, and
394 are <B>ignored</B> since all operations happen in integer space.
395 A positive value rounds to this digit left from the dot. 0 or 1 mean round to
396 integer and are ignore like negative values.
398 See Math::BigInt's bfround() function for details.
400 perl -Mbignum=p,5 -le 'print 123456789+123'
402 Note that setting precision and accuracy at the same time is not possible.
406 This enables a trace mode and is primarily for debugging bigint or
411 Override the built-in hex() method with a version that can handle big
412 integers. This overrides it by exporting it to the current package. Under
413 Perl v5.10.0 and higher, this is not so necessary, as hex() is lexically
414 overridden in the current scope whenever the bigint pragma is active.
418 Override the built-in oct() method with a version that can handle big
419 integers. This overrides it by exporting it to the current package. Under
420 Perl v5.10.0 and higher, this is not so necessary, as oct() is lexically
421 overridden in the current scope whenever the bigint pragma is active.
423 =item l, lib, try or only
425 Load a different math lib, see L<Math Library>.
427 perl -Mbigint=lib,GMP -e 'print 2 ** 512'
428 perl -Mbigint=try,GMP -e 'print 2 ** 512'
429 perl -Mbigint=only,GMP -e 'print 2 ** 512'
431 Currently there is no way to specify more than one library on the command
432 line. This means the following does not work:
434 perl -Mbignum=l,GMP,Pari -e 'print 2 ** 512'
436 This will be hopefully fixed soon ;)
440 This prints out the name and version of all modules used and then exits.
448 Math with the numbers is done (by default) by a module called
449 Math::BigInt::Calc. This is equivalent to saying:
451 use bigint lib => 'Calc';
453 You can change this by using:
455 use bignum lib => 'GMP';
457 The following would first try to find Math::BigInt::Foo, then
458 Math::BigInt::Bar, and when this also fails, revert to Math::BigInt::Calc:
460 use bigint lib => 'Foo,Math::BigInt::Bar';
462 Using C<lib> warns if none of the specified libraries can be found and
463 L<Math::BigInt> did fall back to one of the default libraries.
464 To suppress this warning, use C<try> instead:
466 use bignum try => 'GMP';
468 If you want the code to die instead of falling back, use C<only> instead:
470 use bignum only => 'GMP';
472 Please see respective module documentation for further details.
474 =head2 Internal Format
476 The numbers are stored as objects, and their internals might change at anytime,
477 especially between math operations. The objects also might belong to different
478 classes, like Math::BigInt, or Math::BigInt::Lite. Mixing them together, even
479 with normal scalars is not extraordinary, but normal and expected.
481 You should not depend on the internal format, all accesses must go through
482 accessor methods. E.g. looking at $x->{sign} is not a good idea since there
483 is no guaranty that the object in question has such a hash key, nor is a hash
488 The sign is either '+', '-', 'NaN', '+inf' or '-inf'.
489 You can access it with the sign() method.
491 A sign of 'NaN' is used to represent the result when input arguments are not
492 numbers or as a result of 0/0. '+inf' and '-inf' represent plus respectively
493 minus infinity. You will get '+inf' when dividing a positive number by 0, and
494 '-inf' when dividing any negative number by 0.
498 Since all numbers are now objects, you can use all functions that are part of
499 the BigInt API. You can only use the bxxx() notation, and not the fxxx()
502 But a warning is in order. When using the following to make a copy of a number,
503 only a shallow copy will be made.
508 Using the copy or the original with overloaded math is okay, e.g. the
512 print $x + 1, " ", $y,"\n"; # prints 10 9
514 but calling any method that modifies the number directly will result in
515 B<both> the original and the copy being destroyed:
518 print $x->badd(1), " ", $y,"\n"; # prints 10 10
521 print $x->binc(1), " ", $y,"\n"; # prints 10 10
524 print $x->bmul(2), " ", $y,"\n"; # prints 18 18
526 Using methods that do not modify, but test that the contents works:
529 $z = 9 if $x->is_zero(); # works fine
531 See the documentation about the copy constructor and C<=> in overload, as
532 well as the documentation in BigInt for further details.
540 A shortcut to return Math::BigInt->binf(). Useful because Perl does not always
541 handle bareword C<inf> properly.
545 A shortcut to return Math::BigInt->bnan(). Useful because Perl does not always
546 handle bareword C<NaN> properly.
550 # perl -Mbigint=e -wle 'print e'
552 Returns Euler's number C<e>, aka exp(1). Note that under bigint, this is
553 truncated to an integer, and hence simple '2'.
557 # perl -Mbigint=PI -wle 'print PI'
559 Returns PI. Note that under bigint, this is truncated to an integer, and hence
564 bexp($power,$accuracy);
566 Returns Euler's number C<e> raised to the appropriate power, to
569 Note that under bigint, the result is truncated to an integer.
573 # perl -Mbigint=bexp -wle 'print bexp(1,80)'
579 Returns PI to the wanted accuracy. Note that under bigint, this is truncated
580 to an integer, and hence simple '3'.
584 # perl -Mbigint=bpi -wle 'print bpi(80)'
588 Return the class that numbers are upgraded to, is in fact returning
589 C<$Math::BigInt::upgrade>.
595 print "in effect\n" if bigint::in_effect; # true
598 print "in effect\n" if bigint::in_effect; # false
601 Returns true or false if C<bigint> is in effect in the current scope.
603 This method only works on Perl v5.9.4 or later.
613 Perl does not allow overloading of ranges, so you can neither safely use
614 ranges with bigint endpoints, nor is the iterator variable a bigint.
619 say $i ** $j; # produces a floating-point number,
627 This method only works on Perl v5.9.4 or later.
631 C<bigint> overrides these routines with versions that can also handle
632 big integer values. Under Perl prior to version v5.9.4, however, this
633 will not happen unless you specifically ask for it with the two
634 import tags "hex" and "oct" - and then it will be global and cannot be
635 disabled inside a scope with "no bigint":
637 use bigint qw/hex oct/;
639 print hex("0x1234567890123456");
642 print hex("0x1234567890123456");
645 The second call to hex() will warn about a non-portable constant.
651 # will warn only under Perl older than v5.9.4
652 print hex("0x1234567890123456");
658 C<bigint> is just a thin wrapper around various modules of the Math::BigInt
659 family. Think of it as the head of the family, who runs the shop, and orders
660 the others to do the work.
662 The following modules are currently used by bigint:
664 Math::BigInt::Lite (for speed, and only if it is loadable)
669 Some cool command line examples to impress the Python crowd ;) You might want
670 to compare them to the results under -Mbignum or -Mbigrat:
672 perl -Mbigint -le 'print sqrt(33)'
673 perl -Mbigint -le 'print 2*255'
674 perl -Mbigint -le 'print 4.5+2*255'
675 perl -Mbigint -le 'print 3/7 + 5/7 + 8/3'
676 perl -Mbigint -le 'print 123->is_odd()'
677 perl -Mbigint -le 'print log(2)'
678 perl -Mbigint -le 'print 2 ** 0.5'
679 perl -Mbigint=a,65 -le 'print 2 ** 0.2'
680 perl -Mbignum=a,65,l,GMP -le 'print 7 ** 7777'
684 This program is free software; you may redistribute it and/or modify it under
685 the same terms as Perl itself.
689 Especially L<bigrat> as in C<perl -Mbigrat -le 'print 1/3+1/4'> and
690 L<bignum> as in C<perl -Mbignum -le 'print sqrt(2)'>.
692 L<Math::BigInt>, L<Math::BigRat> and L<Math::Big> as well
693 as L<Math::BigInt::Pari> and L<Math::BigInt::GMP>.
697 (C) by Tels L<http://bloodgate.com/> in early 2002 - 2007.