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