This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
Data::Dumper: Promote dev version to stable release
[perl5.git] / dist / bignum / lib / bigint.pm
CommitLineData
126f3c5f 1package bigint;
9de9b613 2use 5.006;
126f3c5f 3
a7a0833f 4$VERSION = '0.30';
126f3c5f 5use Exporter;
b4bc5691 6@ISA = qw( Exporter );
d98d5fa0
T
7@EXPORT_OK = qw( PI e bpi bexp );
8@EXPORT = qw( inf NaN );
126f3c5f
JH
9
10use strict;
11use overload;
12
13##############################################################################
14
15# These are all alike, and thus faked by AUTOLOAD
16
17my @faked = qw/round_mode accuracy precision div_scale/;
18use vars qw/$VERSION $AUTOLOAD $_lite/; # _lite for testsuite
19
20sub AUTOLOAD
21 {
22 my $name = $AUTOLOAD;
23
24 $name =~ s/.*:://; # split package
25 no strict 'refs';
26 foreach my $n (@faked)
27 {
28 if ($n eq $name)
29 {
30 *{"bigint::$name"} = sub
31 {
32 my $self = shift;
33 no strict 'refs';
34 if (defined $_[0])
35 {
990fb837 36 return Math::BigInt->$name($_[0]);
126f3c5f
JH
37 }
38 return Math::BigInt->$name();
39 };
40 return &$name;
41 }
42 }
43
44 # delayed load of Carp and avoid recursion
45 require Carp;
46 Carp::croak ("Can't call bigint\-\>$name, not a valid method");
47 }
48
49sub upgrade
50 {
95a2d02c 51 $Math::BigInt::upgrade;
126f3c5f
JH
52 }
53
95a2d02c
T
54sub _binary_constant
55 {
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.
59 my $string = shift;
60
61 return Math::BigInt->new($string) if $string =~ /^0[bx]/;
62
63 # so it must be an octal constant
64 Math::BigInt->from_oct($string);
65 }
66
67sub _float_constant
126f3c5f
JH
68 {
69 # this takes a floating point constant string and returns it truncated to
70 # integer. For instance, '4.5' => '4', '1.234e2' => '123' etc
71 my $float = shift;
72
73 # some simple cases first
74 return $float if ($float =~ /^[+-]?[0-9]+$/); # '+123','-1','0' etc
75 return $float
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
79 {
80 $float =~ s/\..*//;
81 return $float;
82 }
9b924220 83 my ($mis,$miv,$mfv,$es,$ev) = Math::BigInt::_split($float);
126f3c5f
JH
84 return $float if !defined $mis; # doesn't look like a number to me
85 my $ec = int($$ev);
86 my $sign = $$mis; $sign = '' if $sign eq '+';
87 if ($$es eq '-')
88 {
89 # ignore fraction part entirely
90 if ($ec >= length($$miv)) # 123.23E-4
91 {
92 return '0';
93 }
94 return $sign . substr ($$miv,0,length($$miv)-$ec); # 1234.45E-2 = 12
95 }
96 # xE+y
97 if ($ec >= length($$mfv))
98 {
99 $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
102 }
103 $mfv = substr($$mfv,0,$ec);
95a2d02c 104 $sign.$$miv.$mfv; # 123.45e+1 => 1234
126f3c5f
JH
105 }
106
4440d13a
T
107sub unimport
108 {
109 $^H{bigint} = undef; # no longer in effect
110 overload::remove_constant('binary','','float','','integer');
111 }
112
113sub in_effect
114 {
115 my $level = shift || 0;
116 my $hinthash = (caller($level))[10];
117 $hinthash->{bigint};
118 }
119
d1a15766
T
120#############################################################################
121# the following two routines are for "use bigint qw/hex oct/;":
122
123sub _hex_global
124 {
125 my $i = $_[0];
126 $i = '0x'.$i unless $i =~ /^0x/;
127 Math::BigInt->new($i);
128 }
129
130sub _oct_global
131 {
132 my $i = $_[0];
133 return Math::BigInt->from_oct($i) if $i =~ /^0[0-7]/;
134 Math::BigInt->new($i);
135 }
136
137#############################################################################
138# the following two routines are for Perl 5.9.4 or later and are lexical
139
140sub _hex
141 {
142 return CORE::hex($_[0]) unless in_effect(1);
143 my $i = $_[0];
144 $i = '0x'.$i unless $i =~ /^0x/;
145 Math::BigInt->new($i);
146 }
147
148sub _oct
149 {
150 return CORE::oct($_[0]) unless in_effect(1);
151 my $i = $_[0];
152 return Math::BigInt->from_oct($i) if $i =~ /^0[0-7]/;
153 Math::BigInt->new($i);
154 }
155
126f3c5f
JH
156sub import
157 {
158 my $self = shift;
159
4440d13a
T
160 $^H{bigint} = 1; # we are in effect
161
075d4edd 162 my ($hex,$oct);
d1a15766
T
163 # for newer Perls always override hex() and oct() with a lexical version:
164 if ($] > 5.009004)
165 {
075d4edd
RGS
166 $oct = \&_oct;
167 $hex = \&_hex;
d1a15766 168 }
126f3c5f 169 # some defaults
bd49aa09 170 my $lib = ''; my $lib_kind = 'try';
126f3c5f
JH
171
172 my @import = ( ':constant' ); # drive it w/ constant
173 my @a = @_; my $l = scalar @_; my $j = 0;
174 my ($ver,$trace); # version? trace?
175 my ($a,$p); # accuracy, precision
176 for ( my $i = 0; $i < $l ; $i++,$j++ )
177 {
bd49aa09 178 if ($_[$i] =~ /^(l|lib|try|only)$/)
126f3c5f
JH
179 {
180 # this causes a different low lib to take care...
bd49aa09 181 $lib_kind = $1; $lib_kind = 'lib' if $lib_kind eq 'l';
126f3c5f 182 $lib = $_[$i+1] || '';
c4a6f826 183 my $s = 2; $s = 1 if @a-$j < 2; # avoid "can not modify non-existent..."
126f3c5f
JH
184 splice @a, $j, $s; $j -= $s; $i++;
185 }
186 elsif ($_[$i] =~ /^(a|accuracy)$/)
187 {
188 $a = $_[$i+1];
c4a6f826 189 my $s = 2; $s = 1 if @a-$j < 2; # avoid "can not modify non-existent..."
126f3c5f
JH
190 splice @a, $j, $s; $j -= $s; $i++;
191 }
192 elsif ($_[$i] =~ /^(p|precision)$/)
193 {
194 $p = $_[$i+1];
c4a6f826 195 my $s = 2; $s = 1 if @a-$j < 2; # avoid "can not modify non-existent..."
126f3c5f
JH
196 splice @a, $j, $s; $j -= $s; $i++;
197 }
198 elsif ($_[$i] =~ /^(v|version)$/)
199 {
200 $ver = 1;
201 splice @a, $j, 1; $j --;
202 }
203 elsif ($_[$i] =~ /^(t|trace)$/)
204 {
205 $trace = 1;
206 splice @a, $j, 1; $j --;
207 }
d1a15766
T
208 elsif ($_[$i] eq 'hex')
209 {
210 splice @a, $j, 1; $j --;
075d4edd 211 $hex = \&_hex_global;
d1a15766
T
212 }
213 elsif ($_[$i] eq 'oct')
214 {
215 splice @a, $j, 1; $j --;
075d4edd 216 $oct = \&_oct_global;
d1a15766 217 }
d98d5fa0 218 elsif ($_[$i] !~ /^(PI|e|bpi|bexp)\z/)
fade31f0
T
219 {
220 die ("unknown option $_[$i]");
221 }
126f3c5f
JH
222 }
223 my $class;
224 $_lite = 0; # using M::BI::L ?
225 if ($trace)
226 {
227 require Math::BigInt::Trace; $class = 'Math::BigInt::Trace';
126f3c5f
JH
228 }
229 else
230 {
231 # see if we can find Math::BigInt::Lite
232 if (!defined $a && !defined $p) # rounding won't work to well
233 {
234 eval 'require Math::BigInt::Lite;';
235 if ($@ eq '')
236 {
237 @import = ( ); # :constant in Lite, not MBI
238 Math::BigInt::Lite->import( ':constant' );
239 $_lite= 1; # signal okay
240 }
241 }
242 require Math::BigInt if $_lite == 0; # not already loaded?
243 $class = 'Math::BigInt'; # regardless of MBIL or not
233f7bc0 244 }
bd49aa09 245 push @import, $lib_kind => $lib if $lib ne '';
126f3c5f 246 # Math::BigInt::Trace or plain Math::BigInt
233f7bc0 247 $class->import(@import);
126f3c5f
JH
248
249 bigint->accuracy($a) if defined $a;
250 bigint->precision($p) if defined $p;
251 if ($ver)
252 {
253 print "bigint\t\t\t v$VERSION\n";
254 print "Math::BigInt::Lite\t v$Math::BigInt::Lite::VERSION\n" if $_lite;
255 print "Math::BigInt\t\t v$Math::BigInt::VERSION";
256 my $config = Math::BigInt->config();
257 print " lib => $config->{lib} v$config->{lib_version}\n";
258 exit;
259 }
260 # we take care of floating point constants, since BigFloat isn't available
261 # and BigInt doesn't like them:
95a2d02c
T
262 overload::constant float => sub { Math::BigInt->new( _float_constant(shift) ); };
263 # Take care of octal/hexadecimal constants
264 overload::constant binary => sub { _binary_constant(shift) };
b4bc5691 265
4440d13a
T
266 # if another big* was already loaded:
267 my ($package) = caller();
268
269 no strict 'refs';
270 if (!defined *{"${package}::inf"})
271 {
fade31f0 272 $self->export_to_level(1,$self,@a); # export inf and NaN, e and PI
4440d13a 273 }
075d4edd
RGS
274 {
275 no warnings 'redefine';
276 *CORE::GLOBAL::oct = $oct if $oct;
277 *CORE::GLOBAL::hex = $hex if $hex;
278 }
126f3c5f
JH
279 }
280
fade31f0
T
281sub inf () { Math::BigInt::binf(); }
282sub NaN () { Math::BigInt::bnan(); }
d98d5fa0
T
283
284sub PI () { Math::BigInt->new(3); }
285sub e () { Math::BigInt->new(2); }
286sub bpi ($) { Math::BigInt->new(3); }
287sub bexp ($$) { my $x = Math::BigInt->new($_[0]); $x->bexp($_[1]); }
b4bc5691 288
126f3c5f
JH
2891;
290
291__END__
292
293=head1 NAME
294
b4bc5691 295bigint - Transparent BigInteger support for Perl
126f3c5f
JH
296
297=head1 SYNOPSIS
298
f9156151 299 use bigint;
126f3c5f
JH
300
301 $x = 2 + 4.5,"\n"; # BigInt 6
b4bc5691
T
302 print 2 ** 512,"\n"; # really is what you think it is
303 print inf + 42,"\n"; # inf
304 print NaN * 7,"\n"; # NaN
d1a15766 305 print hex("0x1234567890123490"),"\n"; # Perl v5.9.4 or later
126f3c5f 306
4440d13a
T
307 {
308 no bigint;
309 print 2 ** 256,"\n"; # a normal Perl scalar now
310 }
311
d1a15766
T
312 # Note that this will be global:
313 use bigint qw/hex oct/;
314 print hex("0x1234567890123490"),"\n";
315 print oct("01234567890123490"),"\n";
316
126f3c5f
JH
317=head1 DESCRIPTION
318
319All operators (including basic math operations) are overloaded. Integer
320constants are created as proper BigInts.
321
1ad2138d
T
322Floating point constants are truncated to integer. All parts and results of
323expressions are also truncated.
324
325Unlike L<integer>, this pragma creates integer constants that are only
326limited in their size by the available memory and CPU time.
327
328=head2 use integer vs. use bigint
329
330There is one small difference between C<use integer> and C<use bigint>: the
331former will not affect assignments to variables and the return value of
332some functions. C<bigint> truncates these results to integer too:
333
334 # perl -Minteger -wle 'print 3.2'
335 3.2
336 # perl -Minteger -wle 'print 3.2 + 0'
337 3
338 # perl -Mbigint -wle 'print 3.2'
339 3
340 # perl -Mbigint -wle 'print 3.2 + 0'
341 3
342
343 # perl -Mbigint -wle 'print exp(1) + 0'
344 2
345 # perl -Mbigint -wle 'print exp(1)'
346 2
d1a15766 347 # perl -Minteger -wle 'print exp(1)'
1ad2138d 348 2.71828182845905
d1a15766 349 # perl -Minteger -wle 'print exp(1) + 0'
1ad2138d
T
350 2
351
352In practice this makes seldom a difference as B<parts and results> of
353expressions will be truncated anyway, but this can, for instance, affect the
354return value of subroutines:
355
ba048c24
FC
356 sub three_integer { use integer; return 3.2; }
357 sub three_bigint { use bigint; return 3.2; }
1ad2138d 358
ba048c24 359 print three_integer(), " ", three_bigint(),"\n"; # prints "3.2 3"
126f3c5f 360
b68b7ab1 361=head2 Options
126f3c5f
JH
362
363bigint recognizes some options that can be passed while loading it via use.
364The options can (currently) be either a single letter form, or the long form.
365The following options exist:
366
367=over 2
368
369=item a or accuracy
370
371This sets the accuracy for all math operations. The argument must be greater
372than or equal to zero. See Math::BigInt's bround() function for details.
373
374 perl -Mbigint=a,2 -le 'print 12345+1'
375
c4a6f826 376Note that setting precision and accuracy at the same time is not possible.
95a2d02c 377
126f3c5f
JH
378=item p or precision
379
380This sets the precision for all math operations. The argument can be any
381integer. Negative values mean a fixed number of digits after the dot, and
382are <B>ignored</B> since all operations happen in integer space.
383A positive value rounds to this digit left from the dot. 0 or 1 mean round to
384integer and are ignore like negative values.
385
386See Math::BigInt's bfround() function for details.
387
388 perl -Mbignum=p,5 -le 'print 123456789+123'
389
c4a6f826 390Note that setting precision and accuracy at the same time is not possible.
95a2d02c 391
126f3c5f
JH
392=item t or trace
393
394This enables a trace mode and is primarily for debugging bigint or
395Math::BigInt.
396
d1a15766
T
397=item hex
398
43cde5e1 399Override the built-in hex() method with a version that can handle big
d1a15766
T
400integers. Note that under Perl v5.9.4 or ealier, this will be global
401and cannot be disabled with "no bigint;".
402
403=item oct
404
43cde5e1 405Override the built-in oct() method with a version that can handle big
d1a15766
T
406integers. Note that under Perl v5.9.4 or ealier, this will be global
407and cannot be disabled with "no bigint;".
408
bd49aa09 409=item l, lib, try or only
126f3c5f 410
bd49aa09 411Load a different math lib, see L<Math Library>.
126f3c5f 412
bd49aa09
SP
413 perl -Mbigint=lib,GMP -e 'print 2 ** 512'
414 perl -Mbigint=try,GMP -e 'print 2 ** 512'
415 perl -Mbigint=only,GMP -e 'print 2 ** 512'
126f3c5f
JH
416
417Currently there is no way to specify more than one library on the command
95a2d02c
T
418line. This means the following does not work:
419
420 perl -Mbignum=l,GMP,Pari -e 'print 2 ** 512'
421
422This will be hopefully fixed soon ;)
126f3c5f
JH
423
424=item v or version
425
426This prints out the name and version of all modules used and then exits.
427
b68b7ab1 428 perl -Mbigint=v
126f3c5f 429
95a2d02c
T
430=back
431
b68b7ab1 432=head2 Math Library
126f3c5f
JH
433
434Math with the numbers is done (by default) by a module called
435Math::BigInt::Calc. This is equivalent to saying:
436
437 use bigint lib => 'Calc';
438
439You can change this by using:
440
bd49aa09 441 use bignum lib => 'GMP';
126f3c5f
JH
442
443The following would first try to find Math::BigInt::Foo, then
444Math::BigInt::Bar, and when this also fails, revert to Math::BigInt::Calc:
445
446 use bigint lib => 'Foo,Math::BigInt::Bar';
447
bd49aa09
SP
448Using C<lib> warns if none of the specified libraries can be found and
449L<Math::BigInt> did fall back to one of the default libraries.
c4a6f826 450To suppress this warning, use C<try> instead:
bd49aa09
SP
451
452 use bignum try => 'GMP';
453
454If you want the code to die instead of falling back, use C<only> instead:
455
456 use bignum only => 'GMP';
457
126f3c5f
JH
458Please see respective module documentation for further details.
459
b68b7ab1 460=head2 Internal Format
126f3c5f
JH
461
462The numbers are stored as objects, and their internals might change at anytime,
463especially between math operations. The objects also might belong to different
464classes, like Math::BigInt, or Math::BigInt::Lite. Mixing them together, even
465with normal scalars is not extraordinary, but normal and expected.
466
467You should not depend on the internal format, all accesses must go through
990fb837 468accessor methods. E.g. looking at $x->{sign} is not a good idea since there
126f3c5f
JH
469is no guaranty that the object in question has such a hash key, nor is a hash
470underneath at all.
471
b68b7ab1 472=head2 Sign
126f3c5f 473
b68b7ab1 474The sign is either '+', '-', 'NaN', '+inf' or '-inf'.
126f3c5f
JH
475You can access it with the sign() method.
476
477A sign of 'NaN' is used to represent the result when input arguments are not
478numbers or as a result of 0/0. '+inf' and '-inf' represent plus respectively
479minus infinity. You will get '+inf' when dividing a positive number by 0, and
480'-inf' when dividing any negative number by 0.
481
a7a0833f 482=head2 Method calls
126f3c5f
JH
483
484Since all numbers are now objects, you can use all functions that are part of
485the BigInt API. You can only use the bxxx() notation, and not the fxxx()
486notation, though.
487
a7a0833f
HS
488But a warning is in order. When using the following to make a copy of a number,
489only a shallow copy will be made.
490
491 $x = 9; $y = $x;
492 $x = $y = 7;
493
494Using the copy or the original with overloaded math is okay, e.g. the
495following work:
496
497 $x = 9; $y = $x;
498 print $x + 1, " ", $y,"\n"; # prints 10 9
499
500but calling any method that modifies the number directly will result in
501B<both> the original and the copy being destroyed:
502
503 $x = 9; $y = $x;
504 print $x->badd(1), " ", $y,"\n"; # prints 10 10
505
506 $x = 9; $y = $x;
507 print $x->binc(1), " ", $y,"\n"; # prints 10 10
508
509 $x = 9; $y = $x;
510 print $x->bmul(2), " ", $y,"\n"; # prints 18 18
511
512Using methods that do not modify, but testthe contents works:
513
514 $x = 9; $y = $x;
515 $z = 9 if $x->is_zero(); # works fine
516
517See the documentation about the copy constructor and C<=> in overload, as
518well as the documentation in BigInt for further details.
519
520=head2 Methods
521
95a2d02c
T
522=over 2
523
524=item inf()
525
526A shortcut to return Math::BigInt->binf(). Useful because Perl does not always
527handle bareword C<inf> properly.
528
529=item NaN()
530
531A shortcut to return Math::BigInt->bnan(). Useful because Perl does not always
532handle bareword C<NaN> properly.
533
d98d5fa0
T
534=item e
535
536 # perl -Mbigint=e -wle 'print e'
537
538Returns Euler's number C<e>, aka exp(1). Note that under bigint, this is
539truncated to an integer, and hence simple '2'.
540
541=item PI
542
543 # perl -Mbigint=PI -wle 'print PI'
544
545Returns PI. Note that under bigint, this is truncated to an integer, and hence
546simple '3'.
547
548=item bexp()
549
550 bexp($power,$accuracy);
551
552Returns Euler's number C<e> raised to the appropriate power, to
553the wanted accuracy.
554
555Note that under bigint, the result is truncated to an integer.
556
557Example:
558
559 # perl -Mbigint=bexp -wle 'print bexp(1,80)'
560
561=item bpi()
562
563 bpi($accuracy);
fade31f0 564
d98d5fa0
T
565Returns PI to the wanted accuracy. Note that under bigint, this is truncated
566to an integer, and hence simple '3'.
fade31f0 567
d98d5fa0 568Example:
fade31f0 569
d98d5fa0 570 # perl -Mbigint=bpi -wle 'print bpi(80)'
fade31f0 571
95a2d02c
T
572=item upgrade()
573
574Return the class that numbers are upgraded to, is in fact returning
575C<$Math::BigInt::upgrade>.
576
4440d13a
T
577=item in_effect()
578
579 use bigint;
580
581 print "in effect\n" if bigint::in_effect; # true
582 {
583 no bigint;
584 print "in effect\n" if bigint::in_effect; # false
585 }
586
587Returns true or false if C<bigint> is in effect in the current scope.
588
589This method only works on Perl v5.9.4 or later.
590
95a2d02c
T
591=back
592
7ed767c4 593=head1 CAVEATS
d1a15766
T
594
595=over 2
596
597=item in_effect()
598
599This method only works on Perl v5.9.4 or later.
600
601=item hex()/oct()
602
603C<bigint> overrides these routines with versions that can also handle
604big integer values. Under Perl prior to version v5.9.4, however, this
605will not happen unless you specifically ask for it with the two
606import tags "hex" and "oct" - and then it will be global and cannot be
607disabled inside a scope with "no bigint":
608
609 use bigint qw/hex oct/;
610
611 print hex("0x1234567890123456");
612 {
613 no bigint;
614 print hex("0x1234567890123456");
615 }
616
617The second call to hex() will warn about a non-portable constant.
618
619Compare this to:
620
621 use bigint;
622
623 # will warn only under Perl older than v5.9.4
624 print hex("0x1234567890123456");
625
626=back
627
126f3c5f
JH
628=head1 MODULES USED
629
630C<bigint> is just a thin wrapper around various modules of the Math::BigInt
631family. Think of it as the head of the family, who runs the shop, and orders
632the others to do the work.
633
634The following modules are currently used by bigint:
635
636 Math::BigInt::Lite (for speed, and only if it is loadable)
637 Math::BigInt
638
639=head1 EXAMPLES
640
641Some cool command line examples to impress the Python crowd ;) You might want
642to compare them to the results under -Mbignum or -Mbigrat:
643
644 perl -Mbigint -le 'print sqrt(33)'
645 perl -Mbigint -le 'print 2*255'
646 perl -Mbigint -le 'print 4.5+2*255'
647 perl -Mbigint -le 'print 3/7 + 5/7 + 8/3'
648 perl -Mbigint -le 'print 123->is_odd()'
649 perl -Mbigint -le 'print log(2)'
650 perl -Mbigint -le 'print 2 ** 0.5'
651 perl -Mbigint=a,65 -le 'print 2 ** 0.2'
95a2d02c 652 perl -Mbignum=a,65,l,GMP -le 'print 7 ** 7777'
126f3c5f
JH
653
654=head1 LICENSE
655
656This program is free software; you may redistribute it and/or modify it under
657the same terms as Perl itself.
658
659=head1 SEE ALSO
660
661Especially L<bigrat> as in C<perl -Mbigrat -le 'print 1/3+1/4'> and
662L<bignum> as in C<perl -Mbignum -le 'print sqrt(2)'>.
663
664L<Math::BigInt>, L<Math::BigRat> and L<Math::Big> as well
665as L<Math::BigInt::BitVect>, L<Math::BigInt::Pari> and L<Math::BigInt::GMP>.
666
667=head1 AUTHORS
668
95a2d02c 669(C) by Tels L<http://bloodgate.com/> in early 2002 - 2007.
126f3c5f
JH
670
671=cut