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