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