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