Math::BigInt take 12 [PATCH]
[p5sagit/p5-mst-13.2.git] / lib / bigint.pm
CommitLineData
126f3c5f 1package bigint;
95a2d02c 2use 5.006002;
126f3c5f 3
4440d13a 4$VERSION = '0.22';
126f3c5f 5use Exporter;
b4bc5691 6@ISA = qw( Exporter );
7@EXPORT_OK = qw( );
8@EXPORT = qw( inf NaN );
126f3c5f 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 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 52 }
53
95a2d02c 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 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 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 105 }
106
4440d13a 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 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 156sub import
157 {
158 my $self = shift;
159
4440d13a 160 $^H{bigint} = 1; # we are in effect
161
075d4edd 162 my ($hex,$oct);
d1a15766 163 # for newer Perls always override hex() and oct() with a lexical version:
164 if ($] > 5.009004)
165 {
075d4edd 166 $oct = \&_oct;
167 $hex = \&_hex;
d1a15766 168 }
126f3c5f 169 # some defaults
bd49aa09 170 my $lib = ''; my $lib_kind = 'try';
126f3c5f 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 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] || '';
183 my $s = 2; $s = 1 if @a-$j < 2; # avoid "can not modify non-existant..."
184 splice @a, $j, $s; $j -= $s; $i++;
185 }
186 elsif ($_[$i] =~ /^(a|accuracy)$/)
187 {
188 $a = $_[$i+1];
189 my $s = 2; $s = 1 if @a-$j < 2; # avoid "can not modify non-existant..."
190 splice @a, $j, $s; $j -= $s; $i++;
191 }
192 elsif ($_[$i] =~ /^(p|precision)$/)
193 {
194 $p = $_[$i+1];
195 my $s = 2; $s = 1 if @a-$j < 2; # avoid "can not modify non-existant..."
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 208 elsif ($_[$i] eq 'hex')
209 {
210 splice @a, $j, 1; $j --;
075d4edd 211 $hex = \&_hex_global;
d1a15766 212 }
213 elsif ($_[$i] eq 'oct')
214 {
215 splice @a, $j, 1; $j --;
075d4edd 216 $oct = \&_oct_global;
d1a15766 217 }
126f3c5f 218 else { die "unknown option $_[$i]"; }
219 }
220 my $class;
221 $_lite = 0; # using M::BI::L ?
222 if ($trace)
223 {
224 require Math::BigInt::Trace; $class = 'Math::BigInt::Trace';
126f3c5f 225 }
226 else
227 {
228 # see if we can find Math::BigInt::Lite
229 if (!defined $a && !defined $p) # rounding won't work to well
230 {
231 eval 'require Math::BigInt::Lite;';
232 if ($@ eq '')
233 {
234 @import = ( ); # :constant in Lite, not MBI
235 Math::BigInt::Lite->import( ':constant' );
236 $_lite= 1; # signal okay
237 }
238 }
239 require Math::BigInt if $_lite == 0; # not already loaded?
240 $class = 'Math::BigInt'; # regardless of MBIL or not
233f7bc0 241 }
bd49aa09 242 push @import, $lib_kind => $lib if $lib ne '';
126f3c5f 243 # Math::BigInt::Trace or plain Math::BigInt
233f7bc0 244 $class->import(@import);
126f3c5f 245
246 bigint->accuracy($a) if defined $a;
247 bigint->precision($p) if defined $p;
248 if ($ver)
249 {
250 print "bigint\t\t\t v$VERSION\n";
251 print "Math::BigInt::Lite\t v$Math::BigInt::Lite::VERSION\n" if $_lite;
252 print "Math::BigInt\t\t v$Math::BigInt::VERSION";
253 my $config = Math::BigInt->config();
254 print " lib => $config->{lib} v$config->{lib_version}\n";
255 exit;
256 }
257 # we take care of floating point constants, since BigFloat isn't available
258 # and BigInt doesn't like them:
95a2d02c 259 overload::constant float => sub { Math::BigInt->new( _float_constant(shift) ); };
260 # Take care of octal/hexadecimal constants
261 overload::constant binary => sub { _binary_constant(shift) };
b4bc5691 262
4440d13a 263 # if another big* was already loaded:
264 my ($package) = caller();
265
266 no strict 'refs';
267 if (!defined *{"${package}::inf"})
268 {
269 $self->export_to_level(1,$self,@a); # export inf and NaN
270 }
075d4edd 271 {
272 no warnings 'redefine';
273 *CORE::GLOBAL::oct = $oct if $oct;
274 *CORE::GLOBAL::hex = $hex if $hex;
275 }
126f3c5f 276 }
277
b4bc5691 278sub inf () { Math::BigInt->binf(); }
279sub NaN () { Math::BigInt->bnan(); }
280
126f3c5f 2811;
282
283__END__
284
285=head1 NAME
286
b4bc5691 287bigint - Transparent BigInteger support for Perl
126f3c5f 288
289=head1 SYNOPSIS
290
f9156151 291 use bigint;
126f3c5f 292
293 $x = 2 + 4.5,"\n"; # BigInt 6
b4bc5691 294 print 2 ** 512,"\n"; # really is what you think it is
295 print inf + 42,"\n"; # inf
296 print NaN * 7,"\n"; # NaN
d1a15766 297 print hex("0x1234567890123490"),"\n"; # Perl v5.9.4 or later
126f3c5f 298
4440d13a 299 {
300 no bigint;
301 print 2 ** 256,"\n"; # a normal Perl scalar now
302 }
303
d1a15766 304 # Note that this will be global:
305 use bigint qw/hex oct/;
306 print hex("0x1234567890123490"),"\n";
307 print oct("01234567890123490"),"\n";
308
126f3c5f 309=head1 DESCRIPTION
310
311All operators (including basic math operations) are overloaded. Integer
312constants are created as proper BigInts.
313
1ad2138d 314Floating point constants are truncated to integer. All parts and results of
315expressions are also truncated.
316
317Unlike L<integer>, this pragma creates integer constants that are only
318limited in their size by the available memory and CPU time.
319
320=head2 use integer vs. use bigint
321
322There is one small difference between C<use integer> and C<use bigint>: the
323former will not affect assignments to variables and the return value of
324some functions. C<bigint> truncates these results to integer too:
325
326 # perl -Minteger -wle 'print 3.2'
327 3.2
328 # perl -Minteger -wle 'print 3.2 + 0'
329 3
330 # perl -Mbigint -wle 'print 3.2'
331 3
332 # perl -Mbigint -wle 'print 3.2 + 0'
333 3
334
335 # perl -Mbigint -wle 'print exp(1) + 0'
336 2
337 # perl -Mbigint -wle 'print exp(1)'
338 2
d1a15766 339 # perl -Minteger -wle 'print exp(1)'
1ad2138d 340 2.71828182845905
d1a15766 341 # perl -Minteger -wle 'print exp(1) + 0'
1ad2138d 342 2
343
344In practice this makes seldom a difference as B<parts and results> of
345expressions will be truncated anyway, but this can, for instance, affect the
346return value of subroutines:
347
348 sub three_integer { use integer; return 3.2; }
349 sub three_bigint { use bigint; return 3.2; }
350
351 print three_integer(), " ", three_bigint(),"\n"; # prints "3.2 3"
126f3c5f 352
b68b7ab1 353=head2 Options
126f3c5f 354
355bigint recognizes some options that can be passed while loading it via use.
356The options can (currently) be either a single letter form, or the long form.
357The following options exist:
358
359=over 2
360
361=item a or accuracy
362
363This sets the accuracy for all math operations. The argument must be greater
364than or equal to zero. See Math::BigInt's bround() function for details.
365
366 perl -Mbigint=a,2 -le 'print 12345+1'
367
95a2d02c 368Note that setting precision and accurary at the same time is not possible.
369
126f3c5f 370=item p or precision
371
372This sets the precision for all math operations. The argument can be any
373integer. Negative values mean a fixed number of digits after the dot, and
374are <B>ignored</B> since all operations happen in integer space.
375A positive value rounds to this digit left from the dot. 0 or 1 mean round to
376integer and are ignore like negative values.
377
378See Math::BigInt's bfround() function for details.
379
380 perl -Mbignum=p,5 -le 'print 123456789+123'
381
95a2d02c 382Note that setting precision and accurary at the same time is not possible.
383
126f3c5f 384=item t or trace
385
386This enables a trace mode and is primarily for debugging bigint or
387Math::BigInt.
388
d1a15766 389=item hex
390
391Override the build-in hex() method with a version that can handle big
392integers. Note that under Perl v5.9.4 or ealier, this will be global
393and cannot be disabled with "no bigint;".
394
395=item oct
396
397Override the build-in oct() method with a version that can handle big
398integers. Note that under Perl v5.9.4 or ealier, this will be global
399and cannot be disabled with "no bigint;".
400
bd49aa09 401=item l, lib, try or only
126f3c5f 402
bd49aa09 403Load a different math lib, see L<Math Library>.
126f3c5f 404
bd49aa09 405 perl -Mbigint=lib,GMP -e 'print 2 ** 512'
406 perl -Mbigint=try,GMP -e 'print 2 ** 512'
407 perl -Mbigint=only,GMP -e 'print 2 ** 512'
126f3c5f 408
409Currently there is no way to specify more than one library on the command
95a2d02c 410line. This means the following does not work:
411
412 perl -Mbignum=l,GMP,Pari -e 'print 2 ** 512'
413
414This will be hopefully fixed soon ;)
126f3c5f 415
416=item v or version
417
418This prints out the name and version of all modules used and then exits.
419
b68b7ab1 420 perl -Mbigint=v
126f3c5f 421
95a2d02c 422=back
423
b68b7ab1 424=head2 Math Library
126f3c5f 425
426Math with the numbers is done (by default) by a module called
427Math::BigInt::Calc. This is equivalent to saying:
428
429 use bigint lib => 'Calc';
430
431You can change this by using:
432
bd49aa09 433 use bignum lib => 'GMP';
126f3c5f 434
435The following would first try to find Math::BigInt::Foo, then
436Math::BigInt::Bar, and when this also fails, revert to Math::BigInt::Calc:
437
438 use bigint lib => 'Foo,Math::BigInt::Bar';
439
bd49aa09 440Using C<lib> warns if none of the specified libraries can be found and
441L<Math::BigInt> did fall back to one of the default libraries.
442To supress this warning, use C<try> instead:
443
444 use bignum try => 'GMP';
445
446If you want the code to die instead of falling back, use C<only> instead:
447
448 use bignum only => 'GMP';
449
126f3c5f 450Please see respective module documentation for further details.
451
b68b7ab1 452=head2 Internal Format
126f3c5f 453
454The numbers are stored as objects, and their internals might change at anytime,
455especially between math operations. The objects also might belong to different
456classes, like Math::BigInt, or Math::BigInt::Lite. Mixing them together, even
457with normal scalars is not extraordinary, but normal and expected.
458
459You should not depend on the internal format, all accesses must go through
990fb837 460accessor methods. E.g. looking at $x->{sign} is not a good idea since there
126f3c5f 461is no guaranty that the object in question has such a hash key, nor is a hash
462underneath at all.
463
b68b7ab1 464=head2 Sign
126f3c5f 465
b68b7ab1 466The sign is either '+', '-', 'NaN', '+inf' or '-inf'.
126f3c5f 467You can access it with the sign() method.
468
469A sign of 'NaN' is used to represent the result when input arguments are not
470numbers or as a result of 0/0. '+inf' and '-inf' represent plus respectively
471minus infinity. You will get '+inf' when dividing a positive number by 0, and
472'-inf' when dividing any negative number by 0.
473
b68b7ab1 474=head2 Methods
126f3c5f 475
476Since all numbers are now objects, you can use all functions that are part of
477the BigInt API. You can only use the bxxx() notation, and not the fxxx()
478notation, though.
479
95a2d02c 480=over 2
481
482=item inf()
483
484A shortcut to return Math::BigInt->binf(). Useful because Perl does not always
485handle bareword C<inf> properly.
486
487=item NaN()
488
489A shortcut to return Math::BigInt->bnan(). Useful because Perl does not always
490handle bareword C<NaN> properly.
491
492=item upgrade()
493
494Return the class that numbers are upgraded to, is in fact returning
495C<$Math::BigInt::upgrade>.
496
4440d13a 497=item in_effect()
498
499 use bigint;
500
501 print "in effect\n" if bigint::in_effect; # true
502 {
503 no bigint;
504 print "in effect\n" if bigint::in_effect; # false
505 }
506
507Returns true or false if C<bigint> is in effect in the current scope.
508
509This method only works on Perl v5.9.4 or later.
510
95a2d02c 511=back
512
513=head2 MATH LIBRARY
514
515Math with the numbers is done (by default) by a module called
516
b68b7ab1 517=head2 Caveat
990fb837 518
519But a warning is in order. When using the following to make a copy of a number,
520only a shallow copy will be made.
521
522 $x = 9; $y = $x;
523 $x = $y = 7;
524
525Using the copy or the original with overloaded math is okay, e.g. the
526following work:
527
528 $x = 9; $y = $x;
529 print $x + 1, " ", $y,"\n"; # prints 10 9
530
531but calling any method that modifies the number directly will result in
3c4b39be 532B<both> the original and the copy being destroyed:
990fb837 533
534 $x = 9; $y = $x;
535 print $x->badd(1), " ", $y,"\n"; # prints 10 10
536
537 $x = 9; $y = $x;
538 print $x->binc(1), " ", $y,"\n"; # prints 10 10
539
540 $x = 9; $y = $x;
541 print $x->bmul(2), " ", $y,"\n"; # prints 18 18
542
543Using methods that do not modify, but testthe contents works:
544
545 $x = 9; $y = $x;
546 $z = 9 if $x->is_zero(); # works fine
547
548See the documentation about the copy constructor and C<=> in overload, as
549well as the documentation in BigInt for further details.
550
d1a15766 551=head1 CAVAETS
552
553=over 2
554
555=item in_effect()
556
557This method only works on Perl v5.9.4 or later.
558
559=item hex()/oct()
560
561C<bigint> overrides these routines with versions that can also handle
562big integer values. Under Perl prior to version v5.9.4, however, this
563will not happen unless you specifically ask for it with the two
564import tags "hex" and "oct" - and then it will be global and cannot be
565disabled inside a scope with "no bigint":
566
567 use bigint qw/hex oct/;
568
569 print hex("0x1234567890123456");
570 {
571 no bigint;
572 print hex("0x1234567890123456");
573 }
574
575The second call to hex() will warn about a non-portable constant.
576
577Compare this to:
578
579 use bigint;
580
581 # will warn only under Perl older than v5.9.4
582 print hex("0x1234567890123456");
583
584=back
585
126f3c5f 586=head1 MODULES USED
587
588C<bigint> is just a thin wrapper around various modules of the Math::BigInt
589family. Think of it as the head of the family, who runs the shop, and orders
590the others to do the work.
591
592The following modules are currently used by bigint:
593
594 Math::BigInt::Lite (for speed, and only if it is loadable)
595 Math::BigInt
596
597=head1 EXAMPLES
598
599Some cool command line examples to impress the Python crowd ;) You might want
600to compare them to the results under -Mbignum or -Mbigrat:
601
602 perl -Mbigint -le 'print sqrt(33)'
603 perl -Mbigint -le 'print 2*255'
604 perl -Mbigint -le 'print 4.5+2*255'
605 perl -Mbigint -le 'print 3/7 + 5/7 + 8/3'
606 perl -Mbigint -le 'print 123->is_odd()'
607 perl -Mbigint -le 'print log(2)'
608 perl -Mbigint -le 'print 2 ** 0.5'
609 perl -Mbigint=a,65 -le 'print 2 ** 0.2'
95a2d02c 610 perl -Mbignum=a,65,l,GMP -le 'print 7 ** 7777'
126f3c5f 611
612=head1 LICENSE
613
614This program is free software; you may redistribute it and/or modify it under
615the same terms as Perl itself.
616
617=head1 SEE ALSO
618
619Especially L<bigrat> as in C<perl -Mbigrat -le 'print 1/3+1/4'> and
620L<bignum> as in C<perl -Mbignum -le 'print sqrt(2)'>.
621
622L<Math::BigInt>, L<Math::BigRat> and L<Math::Big> as well
623as L<Math::BigInt::BitVect>, L<Math::BigInt::Pari> and L<Math::BigInt::GMP>.
624
625=head1 AUTHORS
626
95a2d02c 627(C) by Tels L<http://bloodgate.com/> in early 2002 - 2007.
126f3c5f 628
629=cut