7 @EXPORT_OK = qw( PI e bexp bpi );
8 @EXPORT = qw( inf NaN );
12 require bigint; # no "use" to avoid import being called
14 ##############################################################################
22 # These are all alike, and thus faked by AUTOLOAD
24 my @faked = qw/round_mode accuracy precision div_scale/;
25 use vars qw/$VERSION $AUTOLOAD $_lite/; # _lite for testsuite
31 $name =~ s/.*:://; # split package
33 foreach my $n (@faked)
37 *{"bignum::$name"} = sub
43 Math::BigInt->$name($_[0]);
44 return Math::BigFloat->$name($_[0]);
46 return Math::BigInt->$name();
52 # delayed load of Carp and avoid recursion
54 Carp::croak ("Can't call bignum\-\>$name, not a valid method");
59 $^H{bignum} = undef; # no longer in effect
60 overload::remove_constant('binary','','float','','integer');
65 my $level = shift || 0;
66 my $hinthash = (caller($level))[10];
70 #############################################################################
71 # the following two routines are for Perl 5.9.4 or later and are lexical
75 return CORE::hex($_[0]) unless in_effect(1);
77 $i = '0x'.$i unless $i =~ /^0x/;
78 Math::BigInt->new($i);
83 return CORE::oct($_[0]) unless in_effect(1);
85 return Math::BigInt->from_oct($i) if $i =~ /^0[0-7]/;
86 Math::BigInt->new($i);
93 $^H{bignum} = 1; # we are in effect
97 # for newer Perls override hex() and oct() with a lexical version:
105 my $lib = ''; my $lib_kind = 'try';
106 my $upgrade = 'Math::BigFloat';
107 my $downgrade = 'Math::BigInt';
109 my @import = ( ':constant' ); # drive it w/ constant
110 my @a = @_; my $l = scalar @_; my $j = 0;
111 my ($ver,$trace); # version? trace?
112 my ($a,$p); # accuracy, precision
113 for ( my $i = 0; $i < $l ; $i++,$j++ )
115 if ($_[$i] eq 'upgrade')
117 # this causes upgrading
118 $upgrade = $_[$i+1]; # or undef to disable
119 my $s = 2; $s = 1 if @a-$j < 2; # avoid "can not modify non-existant..."
120 splice @a, $j, $s; $j -= $s; $i++;
122 elsif ($_[$i] eq 'downgrade')
124 # this causes downgrading
125 $downgrade = $_[$i+1]; # or undef to disable
126 my $s = 2; $s = 1 if @a-$j < 2; # avoid "can not modify non-existant..."
127 splice @a, $j, $s; $j -= $s; $i++;
129 elsif ($_[$i] =~ /^(l|lib|try|only)$/)
131 # this causes a different low lib to take care...
132 $lib_kind = $1; $lib_kind = 'lib' if $lib_kind eq 'l';
133 $lib = $_[$i+1] || '';
134 my $s = 2; $s = 1 if @a-$j < 2; # avoid "can not modify non-existant..."
135 splice @a, $j, $s; $j -= $s; $i++;
137 elsif ($_[$i] =~ /^(a|accuracy)$/)
140 my $s = 2; $s = 1 if @a-$j < 2; # avoid "can not modify non-existant..."
141 splice @a, $j, $s; $j -= $s; $i++;
143 elsif ($_[$i] =~ /^(p|precision)$/)
146 my $s = 2; $s = 1 if @a-$j < 2; # avoid "can not modify non-existant..."
147 splice @a, $j, $s; $j -= $s; $i++;
149 elsif ($_[$i] =~ /^(v|version)$/)
152 splice @a, $j, 1; $j --;
154 elsif ($_[$i] =~ /^(t|trace)$/)
157 splice @a, $j, 1; $j --;
159 elsif ($_[$i] eq 'hex')
161 splice @a, $j, 1; $j --;
162 $hex = \&bigint::_hex_global;
164 elsif ($_[$i] eq 'oct')
166 splice @a, $j, 1; $j --;
167 $oct = \&bigint::_oct_global;
169 elsif ($_[$i] !~ /^(PI|e|bexp|bpi)\z/)
171 die ("unknown option $_[$i]");
175 $_lite = 0; # using M::BI::L ?
178 require Math::BigInt::Trace; $class = 'Math::BigInt::Trace';
179 $upgrade = 'Math::BigFloat::Trace';
183 # see if we can find Math::BigInt::Lite
184 if (!defined $a && !defined $p) # rounding won't work to well
186 eval 'require Math::BigInt::Lite;';
189 @import = ( ); # :constant in Lite, not MBI
190 Math::BigInt::Lite->import( ':constant' );
191 $_lite= 1; # signal okay
194 require Math::BigInt if $_lite == 0; # not already loaded?
195 $class = 'Math::BigInt'; # regardless of MBIL or not
197 push @import, $lib_kind => $lib if $lib ne '';
198 # Math::BigInt::Trace or plain Math::BigInt
199 $class->import(@import, upgrade => $upgrade);
203 require Math::BigFloat::Trace; $class = 'Math::BigFloat::Trace';
204 $downgrade = 'Math::BigInt::Trace';
208 require Math::BigFloat; $class = 'Math::BigFloat';
210 $class->import(':constant','downgrade',$downgrade);
212 bignum->accuracy($a) if defined $a;
213 bignum->precision($p) if defined $p;
216 print "bignum\t\t\t v$VERSION\n";
217 print "Math::BigInt::Lite\t v$Math::BigInt::Lite::VERSION\n" if $_lite;
218 print "Math::BigInt\t\t v$Math::BigInt::VERSION";
219 my $config = Math::BigInt->config();
220 print " lib => $config->{lib} v$config->{lib_version}\n";
221 print "Math::BigFloat\t\t v$Math::BigFloat::VERSION\n";
225 # Take care of octal/hexadecimal constants
226 overload::constant binary => sub { bigint::_binary_constant(shift) };
228 # if another big* was already loaded:
229 my ($package) = caller();
232 if (!defined *{"${package}::inf"})
234 $self->export_to_level(1,$self,@a); # export inf and NaN
237 no warnings 'redefine';
238 *CORE::GLOBAL::oct = $oct if $oct;
239 *CORE::GLOBAL::hex = $hex if $hex;
243 sub PI () { Math::BigFloat->new('3.141592653589793238462643383279502884197'); }
244 sub e () { Math::BigFloat->new('2.718281828459045235360287471352662497757'); }
245 sub bpi ($) { Math::BigFloat::bpi(@_); }
246 sub bexp ($$) { my $x = Math::BigFloat->new($_[0]); $x->bexp($_[1]); }
254 bignum - Transparent BigNumber support for Perl
260 $x = 2 + 4.5,"\n"; # BigFloat 6.5
261 print 2 ** 512 * 0.1,"\n"; # really is what you think it is
262 print inf * inf,"\n"; # prints inf
263 print NaN * 3,"\n"; # prints NaN
267 print 2 ** 256,"\n"; # a normal Perl scalar now
270 # for older Perls, note that this will be global:
271 use bignum qw/hex oct/;
272 print hex("0x1234567890123490"),"\n";
273 print oct("01234567890123490"),"\n";
277 All operators (including basic math operations) are overloaded. Integer and
278 floating-point constants are created as proper BigInts or BigFloats,
285 at the top of your script, Math::BigFloat and Math::BigInt will be loaded
286 and any constant number will be converted to an object (Math::BigFloat for
287 floats like 3.1415 and Math::BigInt for integers like 1234).
289 So, the following line:
293 creates actually a Math::BigInt and stores a reference to in $x.
294 This happens transparently and behind your back, so to speak.
296 You can see this with the following:
298 perl -Mbignum -le 'print ref(1234)'
300 Don't worry if it says Math::BigInt::Lite, bignum and friends will use Lite
301 if it is installed since it is faster for some operations. It will be
302 automatically upgraded to BigInt whenever necessary:
304 perl -Mbignum -le 'print ref(2**255)'
306 This also means it is a bad idea to check for some specific package, since
307 the actual contents of $x might be something unexpected. Due to the
308 transparent way of bignum C<ref()> should not be necessary, anyway.
310 Since Math::BigInt and BigFloat also overload the normal math operations,
311 the following line will still work:
313 perl -Mbignum -le 'print ref(1234+1234)'
315 Since numbers are actually objects, you can call all the usual methods from
316 BigInt/BigFloat on them. This even works to some extent on expressions:
318 perl -Mbignum -le '$x = 1234; print $x->bdec()'
319 perl -Mbignum -le 'print 1234->copy()->binc();'
320 perl -Mbignum -le 'print 1234->copy()->binc->badd(6);'
321 perl -Mbignum -le 'print +(1234)->copy()->binc()'
323 (Note that print doesn't do what you expect if the expression starts with
326 You can even chain the operations together as usual:
328 perl -Mbignum -le 'print 1234->copy()->binc->badd(6);'
331 Under bignum (or bigint or bigrat), Perl will "upgrade" the numbers
332 appropriately. This means that:
334 perl -Mbignum -le 'print 1234+4.5'
337 will work correctly. These mixed cases don't do always work when using
338 Math::BigInt or Math::BigFloat alone, or at least not in the way normal Perl
341 If you do want to work with large integers like under C<use integer;>, try
344 perl -Mbigint -le 'print 1234.5+4.5'
347 There is also C<use bigrat;> which gives you big rationals:
349 perl -Mbigrat -le 'print 1234+4.1'
352 The entire upgrading/downgrading is still experimental and might not work
353 as you expect or may even have bugs. You might get errors like this:
355 Can't use an undefined value as an ARRAY reference at
356 /usr/local/lib/perl5/5.8.0/Math/BigInt/Calc.pm line 864
358 This means somewhere a routine got a BigFloat/Lite but expected a BigInt (or
359 vice versa) and the upgrade/downgrad path was missing. This is a bug, please
360 report it so that we can fix it.
362 You might consider using just Math::BigInt or Math::BigFloat, since they
363 allow you finer control over what get's done in which module/space. For
364 instance, simple loop counters will be Math::BigInts under C<use bignum;> and
365 this is slower than keeping them as Perl scalars:
367 perl -Mbignum -le 'for ($i = 0; $i < 10; $i++) { print ref($i); }'
369 Please note the following does not work as expected (prints nothing), since
370 overloading of '..' is not yet possible in Perl (as of v5.8.0):
372 perl -Mbignum -le 'for (1..2) { print ref($_); }'
376 bignum recognizes some options that can be passed while loading it via use.
377 The options can (currently) be either a single letter form, or the long form.
378 The following options exist:
384 This sets the accuracy for all math operations. The argument must be greater
385 than or equal to zero. See Math::BigInt's bround() function for details.
387 perl -Mbignum=a,50 -le 'print sqrt(20)'
389 Note that setting precision and accurary at the same time is not possible.
393 This sets the precision for all math operations. The argument can be any
394 integer. Negative values mean a fixed number of digits after the dot, while
395 a positive value rounds to this digit left from the dot. 0 or 1 mean round to
396 integer. See Math::BigInt's bfround() function for details.
398 perl -Mbignum=p,-50 -le 'print sqrt(20)'
400 Note that setting precision and accurary at the same time is not possible.
404 This enables a trace mode and is primarily for debugging bignum or
405 Math::BigInt/Math::BigFloat.
409 Load a different math lib, see L<MATH LIBRARY>.
411 perl -Mbignum=l,GMP -e 'print 2 ** 512'
413 Currently there is no way to specify more than one library on the command
414 line. This means the following does not work:
416 perl -Mbignum=l,GMP,Pari -e 'print 2 ** 512'
418 This will be hopefully fixed soon ;)
422 Override the built-in hex() method with a version that can handle big
423 integers. Note that under Perl older than v5.9.4, this will be global
424 and cannot be disabled with "no bigint;".
428 Override the built-in oct() method with a version that can handle big
429 integers. Note that under Perl older than v5.9.4, this will be global
430 and cannot be disabled with "no bigint;".
434 This prints out the name and version of all modules used and then exits.
442 Beside import() and AUTOLOAD() there are only a few other methods.
444 Since all numbers are now objects, you can use all functions that are part of
445 the BigInt or BigFloat API. It is wise to use only the bxxx() notation, and not
446 the fxxx() notation, though. This makes it possible that the underlying object
447 might morph into a different class than BigFloat.
451 But a warning is in order. When using the following to make a copy of a number,
452 only a shallow copy will be made.
457 If you want to make a real copy, use the following:
461 Using the copy or the original with overloaded math is okay, e.g. the
465 print $x + 1, " ", $y,"\n"; # prints 10 9
467 but calling any method that modifies the number directly will result in
468 B<both> the original and the copy being destroyed:
471 print $x->badd(1), " ", $y,"\n"; # prints 10 10
474 print $x->binc(1), " ", $y,"\n"; # prints 10 10
477 print $x->bmul(2), " ", $y,"\n"; # prints 18 18
479 Using methods that do not modify, but test the contents works:
482 $z = 9 if $x->is_zero(); # works fine
484 See the documentation about the copy constructor and C<=> in overload, as
485 well as the documentation in BigInt for further details.
491 A shortcut to return Math::BigInt->binf(). Useful because Perl does not always
492 handle bareword C<inf> properly.
496 A shortcut to return Math::BigInt->bnan(). Useful because Perl does not always
497 handle bareword C<NaN> properly.
501 # perl -Mbignum=e -wle 'print e'
503 Returns Euler's number C<e>, aka exp(1).
507 # perl -Mbignum=PI -wle 'print PI'
513 bexp($power,$accuracy);
515 Returns Euler's number C<e> raised to the appropriate power, to
520 # perl -Mbignum=bexp -wle 'print bexp(1,80)'
526 Returns PI to the wanted accuracy.
530 # perl -Mbignum=bpi -wle 'print bpi(80)'
534 Return the class that numbers are upgraded to, is in fact returning
535 C<$Math::BigInt::upgrade>.
541 print "in effect\n" if bignum::in_effect; # true
544 print "in effect\n" if bignum::in_effect; # false
547 Returns true or false if C<bignum> is in effect in the current scope.
549 This method only works on Perl v5.9.4 or later.
555 Math with the numbers is done (by default) by a module called
556 Math::BigInt::Calc. This is equivalent to saying:
558 use bignum lib => 'Calc';
560 You can change this by using:
562 use bignum lib => 'GMP';
564 The following would first try to find Math::BigInt::Foo, then
565 Math::BigInt::Bar, and when this also fails, revert to Math::BigInt::Calc:
567 use bignum lib => 'Foo,Math::BigInt::Bar';
569 Please see respective module documentation for further details.
571 Using C<lib> warns if none of the specified libraries can be found and
572 L<Math::BigInt> did fall back to one of the default libraries.
573 To supress this warning, use C<try> instead:
575 use bignum try => 'GMP';
577 If you want the code to die instead of falling back, use C<only> instead:
579 use bignum only => 'GMP';
581 =head2 INTERNAL FORMAT
583 The numbers are stored as objects, and their internals might change at anytime,
584 especially between math operations. The objects also might belong to different
585 classes, like Math::BigInt, or Math::BigFLoat. Mixing them together, even
586 with normal scalars is not extraordinary, but normal and expected.
588 You should not depend on the internal format, all accesses must go through
589 accessor methods. E.g. looking at $x->{sign} is not a bright idea since there
590 is no guaranty that the object in question has such a hashkey, nor is a hash
595 The sign is either '+', '-', 'NaN', '+inf' or '-inf' and stored seperately.
596 You can access it with the sign() method.
598 A sign of 'NaN' is used to represent the result when input arguments are not
599 numbers or as a result of 0/0. '+inf' and '-inf' represent plus respectively
600 minus infinity. You will get '+inf' when dividing a positive number by 0, and
601 '-inf' when dividing any negative number by 0.
609 This method only works on Perl v5.9.4 or later.
613 C<bigint> overrides these routines with versions that can also handle
614 big integer values. Under Perl prior to version v5.9.4, however, this
615 will not happen unless you specifically ask for it with the two
616 import tags "hex" and "oct" - and then it will be global and cannot be
617 disabled inside a scope with "no bigint":
619 use bigint qw/hex oct/;
621 print hex("0x1234567890123456");
624 print hex("0x1234567890123456");
627 The second call to hex() will warn about a non-portable constant.
633 # will warn only under older than v5.9.4
634 print hex("0x1234567890123456");
640 C<bignum> is just a thin wrapper around various modules of the Math::BigInt
641 family. Think of it as the head of the family, who runs the shop, and orders
642 the others to do the work.
644 The following modules are currently used by bignum:
646 Math::BigInt::Lite (for speed, and only if it is loadable)
652 Some cool command line examples to impress the Python crowd ;)
654 perl -Mbignum -le 'print sqrt(33)'
655 perl -Mbignum -le 'print 2*255'
656 perl -Mbignum -le 'print 4.5+2*255'
657 perl -Mbignum -le 'print 3/7 + 5/7 + 8/3'
658 perl -Mbignum -le 'print 123->is_odd()'
659 perl -Mbignum -le 'print log(2)'
660 perl -Mbignum -le 'print exp(1)'
661 perl -Mbignum -le 'print 2 ** 0.5'
662 perl -Mbignum=a,65 -le 'print 2 ** 0.2'
663 perl -Mbignum=a,65,l,GMP -le 'print 7 ** 7777'
667 This program is free software; you may redistribute it and/or modify it under
668 the same terms as Perl itself.
672 Especially L<bigrat> as in C<perl -Mbigrat -le 'print 1/3+1/4'>.
674 L<Math::BigFloat>, L<Math::BigInt>, L<Math::BigRat> and L<Math::Big> as well
675 as L<Math::BigInt::BitVect>, L<Math::BigInt::Pari> and L<Math::BigInt::GMP>.
679 (C) by Tels L<http://bloodgate.com/> in early 2002 - 2007.