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