5ebb904480557c7c1ed5aa2a39029774174e4d46
[p5sagit/p5-mst-13.2.git] / lib / bignum.pm
1 package bignum;
2 use 5.006002;
3
4 $VERSION = '0.22';
5 use Exporter;
6 @ISA            = qw( bigint );
7 @EXPORT_OK      = qw( ); 
8 @EXPORT         = qw( inf NaN ); 
9
10 use strict;
11 use overload;
12 require bigint;         # no "use" to avoid import being called
13
14 ############################################################################## 
15
16 BEGIN 
17   {
18   *inf = \&bigint::inf;
19   *NaN = \&bigint::NaN;
20   }
21
22 # These are all alike, and thus faked by AUTOLOAD
23
24 my @faked = qw/round_mode accuracy precision div_scale/;
25 use vars qw/$VERSION $AUTOLOAD $_lite/;         # _lite for testsuite
26
27 sub AUTOLOAD
28   {
29   my $name = $AUTOLOAD;
30
31   $name =~ s/.*:://;    # split package
32   no strict 'refs';
33   foreach my $n (@faked)
34     {
35     if ($n eq $name)
36       {
37       *{"bignum::$name"} = sub 
38         {
39         my $self = shift;
40         no strict 'refs';
41         if (defined $_[0])
42           {
43           Math::BigInt->$name($_[0]);
44           return Math::BigFloat->$name($_[0]);
45           }
46         return Math::BigInt->$name();
47         };
48       return &$name;
49       }
50     }
51  
52   # delayed load of Carp and avoid recursion
53   require Carp;
54   Carp::croak ("Can't call bignum\-\>$name, not a valid method");
55   }
56
57 sub unimport
58   {
59   $^H{bignum} = undef;                                  # no longer in effect
60   overload::remove_constant('binary','','float','','integer');
61   }
62
63 sub in_effect
64   {
65   my $level = shift || 0;
66   my $hinthash = (caller($level))[10];
67   $hinthash->{bignum};
68   }
69
70 #############################################################################
71 # the following two routines are for Perl 5.9.4 or later and are lexical
72
73 sub _hex
74   {
75   return CORE::hex($_[0]) unless in_effect(1);
76   my $i = $_[0];
77   $i = '0x'.$i unless $i =~ /^0x/;
78   Math::BigInt->new($i);
79   }
80
81 sub _oct
82   {
83   return CORE::oct($_[0]) unless in_effect(1);
84   my $i = $_[0];
85   return Math::BigInt->from_oct($i) if $i =~ /^0[0-7]/;
86   Math::BigInt->new($i);
87   }
88
89 sub import 
90   {
91   my $self = shift;
92
93   $^H{bignum} = 1;                                      # we are in effect
94
95   my ($hex,$oct);
96
97   # for newer Perls override hex() and oct() with a lexical version:
98   if ($] > 5.009003)
99     {
100     $hex = \&_hex;
101     $oct = \&_oct;
102     }
103
104   # some defaults
105   my $lib = ''; my $lib_kind = 'try';
106   my $upgrade = 'Math::BigFloat';
107   my $downgrade = 'Math::BigInt';
108
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++ )
114     {
115     if ($_[$i] eq 'upgrade')
116       {
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++;
121       }
122     elsif ($_[$i] eq 'downgrade')
123       {
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++;
128       }
129     elsif ($_[$i] =~ /^(l|lib|try|only)$/)
130       {
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++;
136       }
137     elsif ($_[$i] =~ /^(a|accuracy)$/)
138       {
139       $a = $_[$i+1];
140       my $s = 2; $s = 1 if @a-$j < 2;   # avoid "can not modify non-existant..."
141       splice @a, $j, $s; $j -= $s; $i++;
142       }
143     elsif ($_[$i] =~ /^(p|precision)$/)
144       {
145       $p = $_[$i+1];
146       my $s = 2; $s = 1 if @a-$j < 2;   # avoid "can not modify non-existant..."
147       splice @a, $j, $s; $j -= $s; $i++;
148       }
149     elsif ($_[$i] =~ /^(v|version)$/)
150       {
151       $ver = 1;
152       splice @a, $j, 1; $j --;
153       }
154     elsif ($_[$i] =~ /^(t|trace)$/)
155       {
156       $trace = 1;
157       splice @a, $j, 1; $j --;
158       }
159     elsif ($_[$i] eq 'hex')
160       {
161       splice @a, $j, 1; $j --;
162       $hex = \&bigint::_hex_global;
163       }
164     elsif ($_[$i] eq 'oct')
165       {
166       splice @a, $j, 1; $j --;
167       $oct = \&bigint::_oct_global;
168       }
169     else { die "unknown option $_[$i]"; }
170     }
171   my $class;
172   $_lite = 0;                                   # using M::BI::L ?
173   if ($trace)
174     {
175     require Math::BigInt::Trace; $class = 'Math::BigInt::Trace';
176     $upgrade = 'Math::BigFloat::Trace'; 
177     }
178   else
179     {
180     # see if we can find Math::BigInt::Lite
181     if (!defined $a && !defined $p)             # rounding won't work to well
182       {
183       eval 'require Math::BigInt::Lite;';
184       if ($@ eq '')
185         {
186         @import = ( );                          # :constant in Lite, not MBI
187         Math::BigInt::Lite->import( ':constant' );
188         $_lite= 1;                              # signal okay
189         }
190       }
191     require Math::BigInt if $_lite == 0;        # not already loaded?
192     $class = 'Math::BigInt';                    # regardless of MBIL or not
193     }
194   push @import, $lib_kind => $lib if $lib ne ''; 
195   # Math::BigInt::Trace or plain Math::BigInt
196   $class->import(@import, upgrade => $upgrade);
197
198   if ($trace)
199     {
200     require Math::BigFloat::Trace; $class = 'Math::BigFloat::Trace';
201     $downgrade = 'Math::BigInt::Trace'; 
202     }
203   else
204     {
205     require Math::BigFloat; $class = 'Math::BigFloat';
206     }
207   $class->import(':constant','downgrade',$downgrade);
208
209   bignum->accuracy($a) if defined $a;
210   bignum->precision($p) if defined $p;
211   if ($ver)
212     {
213     print "bignum\t\t\t v$VERSION\n";
214     print "Math::BigInt::Lite\t v$Math::BigInt::Lite::VERSION\n" if $_lite;
215     print "Math::BigInt\t\t v$Math::BigInt::VERSION";
216     my $config = Math::BigInt->config();
217     print " lib => $config->{lib} v$config->{lib_version}\n";
218     print "Math::BigFloat\t\t v$Math::BigFloat::VERSION\n";
219     exit;
220     }
221
222   # Take care of octal/hexadecimal constants
223   overload::constant binary => sub { bigint::_binary_constant(shift) };
224
225   # if another big* was already loaded:
226   my ($package) = caller();
227
228   no strict 'refs';
229   if (!defined *{"${package}::inf"})
230     {
231     $self->export_to_level(1,$self,@a);           # export inf and NaN
232     }
233   {
234     no warnings 'redefine';
235     *CORE::GLOBAL::oct = $oct if $oct;
236     *CORE::GLOBAL::hex = $hex if $hex;
237   }
238   }
239
240 1;
241
242 __END__
243
244 =head1 NAME
245
246 bignum - Transparent BigNumber support for Perl
247
248 =head1 SYNOPSIS
249
250   use bignum;
251
252   $x = 2 + 4.5,"\n";                    # BigFloat 6.5
253   print 2 ** 512 * 0.1,"\n";            # really is what you think it is
254   print inf * inf,"\n";                 # prints inf
255   print NaN * 3,"\n";                   # prints NaN
256
257   {
258     no bignum;
259     print 2 ** 256,"\n";                # a normal Perl scalar now
260   }
261
262   # for older Perls, note that this will be global:
263   use bignum qw/hex oct/;
264   print hex("0x1234567890123490"),"\n";
265   print oct("01234567890123490"),"\n";
266
267 =head1 DESCRIPTION
268
269 All operators (including basic math operations) are overloaded. Integer and
270 floating-point constants are created as proper BigInts or BigFloats,
271 respectively.
272
273 If you do 
274
275         use bignum;
276
277 at the top of your script, Math::BigFloat and Math::BigInt will be loaded
278 and any constant number will be converted to an object (Math::BigFloat for
279 floats like 3.1415 and Math::BigInt for integers like 1234).
280
281 So, the following line:
282
283         $x = 1234;
284
285 creates actually a Math::BigInt and stores a reference to in $x.
286 This happens transparently and behind your back, so to speak.
287
288 You can see this with the following:
289
290         perl -Mbignum -le 'print ref(1234)'
291
292 Don't worry if it says Math::BigInt::Lite, bignum and friends will use Lite
293 if it is installed since it is faster for some operations. It will be
294 automatically upgraded to BigInt whenever necessary:
295
296         perl -Mbignum -le 'print ref(2**255)'
297
298 This also means it is a bad idea to check for some specific package, since
299 the actual contents of $x might be something unexpected. Due to the
300 transparent way of bignum C<ref()> should not be necessary, anyway.
301
302 Since Math::BigInt and BigFloat also overload the normal math operations,
303 the following line will still work:
304
305         perl -Mbignum -le 'print ref(1234+1234)'
306
307 Since numbers are actually objects, you can call all the usual methods from
308 BigInt/BigFloat on them. This even works to some extent on expressions:
309
310         perl -Mbignum -le '$x = 1234; print $x->bdec()'
311         perl -Mbignum -le 'print 1234->copy()->binc();'
312         perl -Mbignum -le 'print 1234->copy()->binc->badd(6);'
313         perl -Mbignum -le 'print +(1234)->copy()->binc()'
314
315 (Note that print doesn't do what you expect if the expression starts with
316 '(' hence the C<+>)
317
318 You can even chain the operations together as usual:
319
320         perl -Mbignum -le 'print 1234->copy()->binc->badd(6);'
321         1241
322
323 Under bignum (or bigint or bigrat), Perl will "upgrade" the numbers
324 appropriately. This means that:
325
326         perl -Mbignum -le 'print 1234+4.5'
327         1238.5
328
329 will work correctly. These mixed cases don't do always work when using
330 Math::BigInt or Math::BigFloat alone, or at least not in the way normal Perl
331 scalars work. 
332
333 If you do want to work with large integers like under C<use integer;>, try
334 C<use bigint;>:
335
336         perl -Mbigint -le 'print 1234.5+4.5'
337         1238
338
339 There is also C<use bigrat;> which gives you big rationals:
340
341         perl -Mbigrat -le 'print 1234+4.1'
342         12381/10
343
344 The entire upgrading/downgrading is still experimental and might not work
345 as you expect or may even have bugs. You might get errors like this:
346
347         Can't use an undefined value as an ARRAY reference at
348         /usr/local/lib/perl5/5.8.0/Math/BigInt/Calc.pm line 864
349
350 This means somewhere a routine got a BigFloat/Lite but expected a BigInt (or
351 vice versa) and the upgrade/downgrad path was missing. This is a bug, please
352 report it so that we can fix it.
353
354 You might consider using just Math::BigInt or Math::BigFloat, since they
355 allow you finer control over what get's done in which module/space. For
356 instance, simple loop counters will be Math::BigInts under C<use bignum;> and
357 this is slower than keeping them as Perl scalars:
358
359         perl -Mbignum -le 'for ($i = 0; $i < 10; $i++) { print ref($i); }'
360
361 Please note the following does not work as expected (prints nothing), since
362 overloading of '..' is not yet possible in Perl (as of v5.8.0):
363
364         perl -Mbignum -le 'for (1..2) { print ref($_); }'
365
366 =head2 Options
367
368 bignum recognizes some options that can be passed while loading it via use.
369 The options can (currently) be either a single letter form, or the long form.
370 The following options exist:
371
372 =over 2
373
374 =item a or accuracy
375
376 This sets the accuracy for all math operations. The argument must be greater
377 than or equal to zero. See Math::BigInt's bround() function for details.
378
379         perl -Mbignum=a,50 -le 'print sqrt(20)'
380
381 Note that setting precision and accurary at the same time is not possible.
382
383 =item p or precision
384
385 This sets the precision for all math operations. The argument can be any
386 integer. Negative values mean a fixed number of digits after the dot, while
387 a positive value rounds to this digit left from the dot. 0 or 1 mean round to
388 integer. See Math::BigInt's bfround() function for details.
389
390         perl -Mbignum=p,-50 -le 'print sqrt(20)'
391
392 Note that setting precision and accurary at the same time is not possible.
393
394 =item t or trace
395
396 This enables a trace mode and is primarily for debugging bignum or
397 Math::BigInt/Math::BigFloat.
398
399 =item l or lib
400
401 Load a different math lib, see L<MATH LIBRARY>.
402
403         perl -Mbignum=l,GMP -e 'print 2 ** 512'
404
405 Currently there is no way to specify more than one library on the command
406 line. This means the following does not work:
407
408         perl -Mbignum=l,GMP,Pari -e 'print 2 ** 512'
409
410 This will be hopefully fixed soon ;)
411
412 =item hex
413
414 Override the build-in hex() method with a version that can handle big
415 integers. Note that under Perl older than v5.9.4, this will be global
416 and cannot be disabled with "no bigint;".
417
418 =item oct
419
420 Override the build-in oct() method with a version that can handle big
421 integers. Note that under Perl older than v5.9.4, this will be global
422 and cannot be disabled with "no bigint;".
423
424 =item v or version
425
426 This prints out the name and version of all modules used and then exits.
427
428         perl -Mbignum=v
429
430 =back
431
432 =head2 Methods
433
434 Beside import() and AUTOLOAD() there are only a few other methods.
435
436 Since all numbers are now objects, you can use all functions that are part of
437 the BigInt or BigFloat API. It is wise to use only the bxxx() notation, and not
438 the fxxx() notation, though. This makes it possible that the underlying object
439 might morph into a different class than BigFloat.
440
441 =head2 Caveats
442
443 But a warning is in order. When using the following to make a copy of a number,
444 only a shallow copy will be made.
445
446         $x = 9; $y = $x;
447         $x = $y = 7;
448
449 If you want to make a real copy, use the following:
450
451         $y = $x->copy();
452
453 Using the copy or the original with overloaded math is okay, e.g. the
454 following work:
455
456         $x = 9; $y = $x;
457         print $x + 1, " ", $y,"\n";     # prints 10 9
458
459 but calling any method that modifies the number directly will result in
460 B<both> the original and the copy being destroyed:
461
462         $x = 9; $y = $x;
463         print $x->badd(1), " ", $y,"\n";        # prints 10 10
464
465         $x = 9; $y = $x;
466         print $x->binc(1), " ", $y,"\n";        # prints 10 10
467
468         $x = 9; $y = $x;
469         print $x->bmul(2), " ", $y,"\n";        # prints 18 18
470
471 Using methods that do not modify, but test the contents works:
472
473         $x = 9; $y = $x;
474         $z = 9 if $x->is_zero();                # works fine
475
476 See the documentation about the copy constructor and C<=> in overload, as
477 well as the documentation in BigInt for further details.
478
479 =over 2
480
481 =item inf()
482
483 A shortcut to return Math::BigInt->binf(). Useful because Perl does not always
484 handle bareword C<inf> properly.
485
486 =item NaN()
487
488 A shortcut to return Math::BigInt->bnan(). Useful because Perl does not always
489 handle bareword C<NaN> properly.
490
491 =item upgrade()
492
493 Return the class that numbers are upgraded to, is in fact returning
494 C<$Math::BigInt::upgrade>.
495
496 =item in_effect()
497
498         use bignum;
499
500         print "in effect\n" if bignum::in_effect;       # true
501         {
502           no bignum;
503           print "in effect\n" if bignum::in_effect;     # false
504         }
505
506 Returns true or false if C<bignum> is in effect in the current scope.
507
508 This method only works on Perl v5.9.4 or later.
509
510 =back
511
512 =head2 Math Library
513
514 Math with the numbers is done (by default) by a module called
515 Math::BigInt::Calc. This is equivalent to saying:
516
517         use bignum lib => 'Calc';
518
519 You can change this by using:
520
521         use bignum lib => 'GMP';
522
523 The following would first try to find Math::BigInt::Foo, then
524 Math::BigInt::Bar, and when this also fails, revert to Math::BigInt::Calc:
525
526         use bignum lib => 'Foo,Math::BigInt::Bar';
527
528 Please see respective module documentation for further details.
529
530 Using C<lib> warns if none of the specified libraries can be found and
531 L<Math::BigInt> did fall back to one of the default libraries.
532 To supress this warning, use C<try> instead:
533
534         use bignum try => 'GMP';
535
536 If you want the code to die instead of falling back, use C<only> instead:
537
538         use bignum only => 'GMP';
539
540 =head2 INTERNAL FORMAT
541
542 The numbers are stored as objects, and their internals might change at anytime,
543 especially between math operations. The objects also might belong to different
544 classes, like Math::BigInt, or Math::BigFLoat. Mixing them together, even
545 with normal scalars is not extraordinary, but normal and expected.
546
547 You should not depend on the internal format, all accesses must go through
548 accessor methods. E.g. looking at $x->{sign} is not a bright idea since there
549 is no guaranty that the object in question has such a hashkey, nor is a hash
550 underneath at all.
551
552 =head2 SIGN
553
554 The sign is either '+', '-', 'NaN', '+inf' or '-inf' and stored seperately.
555 You can access it with the sign() method.
556
557 A sign of 'NaN' is used to represent the result when input arguments are not
558 numbers or as a result of 0/0. '+inf' and '-inf' represent plus respectively
559 minus infinity. You will get '+inf' when dividing a positive number by 0, and
560 '-inf' when dividing any negative number by 0.
561
562 =head1 CAVAETS
563
564 =over 2
565
566 =item in_effect()
567
568 This method only works on Perl v5.9.4 or later.
569
570 =item hex()/oct()
571
572 C<bigint> overrides these routines with versions that can also handle
573 big integer values. Under Perl prior to version v5.9.4, however, this
574 will not happen unless you specifically ask for it with the two
575 import tags "hex" and "oct" - and then it will be global and cannot be
576 disabled inside a scope with "no bigint":
577
578         use bigint qw/hex oct/;
579
580         print hex("0x1234567890123456");
581         {
582                 no bigint;
583                 print hex("0x1234567890123456");
584         }
585
586 The second call to hex() will warn about a non-portable constant.
587
588 Compare this to:
589
590         use bigint;
591
592         # will warn only under older than v5.9.4
593         print hex("0x1234567890123456");
594
595 =back
596
597 =head1 MODULES USED
598
599 C<bignum> is just a thin wrapper around various modules of the Math::BigInt
600 family. Think of it as the head of the family, who runs the shop, and orders
601 the others to do the work.
602
603 The following modules are currently used by bignum:
604
605         Math::BigInt::Lite      (for speed, and only if it is loadable)
606         Math::BigInt
607         Math::BigFloat
608
609 =head1 EXAMPLES
610
611 Some cool command line examples to impress the Python crowd ;)
612  
613         perl -Mbignum -le 'print sqrt(33)'
614         perl -Mbignum -le 'print 2*255'
615         perl -Mbignum -le 'print 4.5+2*255'
616         perl -Mbignum -le 'print 3/7 + 5/7 + 8/3'
617         perl -Mbignum -le 'print 123->is_odd()'
618         perl -Mbignum -le 'print log(2)'
619         perl -Mbignum -le 'print exp(1)'
620         perl -Mbignum -le 'print 2 ** 0.5'
621         perl -Mbignum=a,65 -le 'print 2 ** 0.2'
622         perl -Mbignum=a,65,l,GMP -le 'print 7 ** 7777'
623
624 =head1 LICENSE
625
626 This program is free software; you may redistribute it and/or modify it under
627 the same terms as Perl itself.
628
629 =head1 SEE ALSO
630
631 Especially L<bigrat> as in C<perl -Mbigrat -le 'print 1/3+1/4'>.
632
633 L<Math::BigFloat>, L<Math::BigInt>, L<Math::BigRat> and L<Math::Big> as well
634 as L<Math::BigInt::BitVect>, L<Math::BigInt::Pari> and  L<Math::BigInt::GMP>.
635
636 =head1 AUTHORS
637
638 (C) by Tels L<http://bloodgate.com/> in early 2002 - 2007.
639
640 =cut