Some escapes were mentioned twice, although they're not qr//-specific
[p5sagit/p5-mst-13.2.git] / lib / bignum.pm
CommitLineData
126f3c5f 1package bignum;
95a2d02c 2use 5.006002;
126f3c5f 3
4440d13a 4$VERSION = '0.22';
126f3c5f 5use Exporter;
d1a15766 6@ISA = qw( bigint );
d98d5fa0 7@EXPORT_OK = qw( PI e bexp bpi );
b4bc5691 8@EXPORT = qw( inf NaN );
126f3c5f 9
10use strict;
95a2d02c 11use overload;
d1a15766 12require bigint; # no "use" to avoid import being called
126f3c5f 13
14##############################################################################
15
d1a15766 16BEGIN
17 {
18 *inf = \&bigint::inf;
19 *NaN = \&bigint::NaN;
20 }
21
126f3c5f 22# These are all alike, and thus faked by AUTOLOAD
23
24my @faked = qw/round_mode accuracy precision div_scale/;
25use vars qw/$VERSION $AUTOLOAD $_lite/; # _lite for testsuite
26
27sub 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]);
990fb837 44 return Math::BigFloat->$name($_[0]);
126f3c5f 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
4440d13a 57sub unimport
58 {
59 $^H{bignum} = undef; # no longer in effect
60 overload::remove_constant('binary','','float','','integer');
61 }
62
63sub in_effect
64 {
65 my $level = shift || 0;
66 my $hinthash = (caller($level))[10];
67 $hinthash->{bignum};
68 }
69
d1a15766 70#############################################################################
71# the following two routines are for Perl 5.9.4 or later and are lexical
72
73sub _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
81sub _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
126f3c5f 89sub import
90 {
91 my $self = shift;
92
4440d13a 93 $^H{bignum} = 1; # we are in effect
94
075d4edd 95 my ($hex,$oct);
96
d1a15766 97 # for newer Perls override hex() and oct() with a lexical version:
98 if ($] > 5.009003)
99 {
075d4edd 100 $hex = \&_hex;
101 $oct = \&_oct;
d1a15766 102 }
103
126f3c5f 104 # some defaults
bd49aa09 105 my $lib = ''; my $lib_kind = 'try';
126f3c5f 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 }
bd49aa09 129 elsif ($_[$i] =~ /^(l|lib|try|only)$/)
126f3c5f 130 {
131 # this causes a different low lib to take care...
bd49aa09 132 $lib_kind = $1; $lib_kind = 'lib' if $lib_kind eq 'l';
126f3c5f 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 }
d1a15766 159 elsif ($_[$i] eq 'hex')
160 {
161 splice @a, $j, 1; $j --;
075d4edd 162 $hex = \&bigint::_hex_global;
d1a15766 163 }
164 elsif ($_[$i] eq 'oct')
165 {
166 splice @a, $j, 1; $j --;
075d4edd 167 $oct = \&bigint::_oct_global;
d1a15766 168 }
d98d5fa0 169 elsif ($_[$i] !~ /^(PI|e|bexp|bpi)\z/)
fade31f0 170 {
171 die ("unknown option $_[$i]");
172 }
126f3c5f 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';
126f3c5f 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
233f7bc0 196 }
48441d71 197 push @import, $lib_kind => $lib if $lib ne '';
126f3c5f 198 # Math::BigInt::Trace or plain Math::BigInt
233f7bc0 199 $class->import(@import, upgrade => $upgrade);
126f3c5f 200
201 if ($trace)
202 {
203 require Math::BigFloat::Trace; $class = 'Math::BigFloat::Trace';
204 $downgrade = 'Math::BigInt::Trace';
126f3c5f 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 }
95a2d02c 224
225 # Take care of octal/hexadecimal constants
d1a15766 226 overload::constant binary => sub { bigint::_binary_constant(shift) };
95a2d02c 227
4440d13a 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 }
075d4edd 236 {
237 no warnings 'redefine';
238 *CORE::GLOBAL::oct = $oct if $oct;
239 *CORE::GLOBAL::hex = $hex if $hex;
240 }
126f3c5f 241 }
242
d98d5fa0 243sub PI () { Math::BigFloat->new('3.141592653589793238462643383279502884197'); }
244sub e () { Math::BigFloat->new('2.718281828459045235360287471352662497757'); }
245sub bpi ($) { Math::BigFloat::bpi(@_); }
246sub bexp ($$) { my $x = Math::BigFloat->new($_[0]); $x->bexp($_[1]); }
fade31f0 247
126f3c5f 2481;
249
250__END__
251
252=head1 NAME
253
254bignum - Transparent BigNumber support for Perl
255
256=head1 SYNOPSIS
257
258 use bignum;
259
260 $x = 2 + 4.5,"\n"; # BigFloat 6.5
b4bc5691 261 print 2 ** 512 * 0.1,"\n"; # really is what you think it is
262 print inf * inf,"\n"; # prints inf
263 print NaN * 3,"\n"; # prints NaN
126f3c5f 264
4440d13a 265 {
266 no bignum;
267 print 2 ** 256,"\n"; # a normal Perl scalar now
268 }
269
d1a15766 270 # for older Perls, note that this will be global:
271 use bignum qw/hex oct/;
272 print hex("0x1234567890123490"),"\n";
273 print oct("01234567890123490"),"\n";
274
126f3c5f 275=head1 DESCRIPTION
276
277All operators (including basic math operations) are overloaded. Integer and
278floating-point constants are created as proper BigInts or BigFloats,
279respectively.
280
24716a00 281If you do
282
283 use bignum;
284
285at the top of your script, Math::BigFloat and Math::BigInt will be loaded
286and any constant number will be converted to an object (Math::BigFloat for
287floats like 3.1415 and Math::BigInt for integers like 1234).
288
289So, the following line:
290
291 $x = 1234;
292
293creates actually a Math::BigInt and stores a reference to in $x.
294This happens transparently and behind your back, so to speak.
295
296You can see this with the following:
297
298 perl -Mbignum -le 'print ref(1234)'
299
300Don't worry if it says Math::BigInt::Lite, bignum and friends will use Lite
301if it is installed since it is faster for some operations. It will be
3c4b39be 302automatically upgraded to BigInt whenever necessary:
24716a00 303
304 perl -Mbignum -le 'print ref(2**255)'
305
306This also means it is a bad idea to check for some specific package, since
307the actual contents of $x might be something unexpected. Due to the
3c4b39be 308transparent way of bignum C<ref()> should not be necessary, anyway.
24716a00 309
310Since Math::BigInt and BigFloat also overload the normal math operations,
311the following line will still work:
312
313 perl -Mbignum -le 'print ref(1234+1234)'
314
315Since numbers are actually objects, you can call all the usual methods from
316BigInt/BigFloat on them. This even works to some extent on expressions:
317
318 perl -Mbignum -le '$x = 1234; print $x->bdec()'
d1a15766 319 perl -Mbignum -le 'print 1234->copy()->binc();'
320 perl -Mbignum -le 'print 1234->copy()->binc->badd(6);'
321 perl -Mbignum -le 'print +(1234)->copy()->binc()'
24716a00 322
323(Note that print doesn't do what you expect if the expression starts with
324'(' hence the C<+>)
325
326You can even chain the operations together as usual:
327
d1a15766 328 perl -Mbignum -le 'print 1234->copy()->binc->badd(6);'
24716a00 329 1241
330
331Under bignum (or bigint or bigrat), Perl will "upgrade" the numbers
332appropriately. This means that:
333
334 perl -Mbignum -le 'print 1234+4.5'
335 1238.5
336
337will work correctly. These mixed cases don't do always work when using
338Math::BigInt or Math::BigFloat alone, or at least not in the way normal Perl
339scalars work.
340
341If you do want to work with large integers like under C<use integer;>, try
342C<use bigint;>:
343
344 perl -Mbigint -le 'print 1234.5+4.5'
345 1238
346
347There is also C<use bigrat;> which gives you big rationals:
348
349 perl -Mbigrat -le 'print 1234+4.1'
350 12381/10
351
352The entire upgrading/downgrading is still experimental and might not work
d1a15766 353as you expect or may even have bugs. You might get errors like this:
24716a00 354
355 Can't use an undefined value as an ARRAY reference at
356 /usr/local/lib/perl5/5.8.0/Math/BigInt/Calc.pm line 864
357
358This means somewhere a routine got a BigFloat/Lite but expected a BigInt (or
359vice versa) and the upgrade/downgrad path was missing. This is a bug, please
360report it so that we can fix it.
361
362You might consider using just Math::BigInt or Math::BigFloat, since they
363allow you finer control over what get's done in which module/space. For
364instance, simple loop counters will be Math::BigInts under C<use bignum;> and
365this is slower than keeping them as Perl scalars:
366
367 perl -Mbignum -le 'for ($i = 0; $i < 10; $i++) { print ref($i); }'
368
369Please note the following does not work as expected (prints nothing), since
370overloading of '..' is not yet possible in Perl (as of v5.8.0):
371
372 perl -Mbignum -le 'for (1..2) { print ref($_); }'
373
b68b7ab1 374=head2 Options
126f3c5f 375
376bignum recognizes some options that can be passed while loading it via use.
377The options can (currently) be either a single letter form, or the long form.
378The following options exist:
379
380=over 2
381
382=item a or accuracy
383
384This sets the accuracy for all math operations. The argument must be greater
385than or equal to zero. See Math::BigInt's bround() function for details.
386
387 perl -Mbignum=a,50 -le 'print sqrt(20)'
388
95a2d02c 389Note that setting precision and accurary at the same time is not possible.
390
126f3c5f 391=item p or precision
392
393This sets the precision for all math operations. The argument can be any
394integer. Negative values mean a fixed number of digits after the dot, while
395a positive value rounds to this digit left from the dot. 0 or 1 mean round to
396integer. See Math::BigInt's bfround() function for details.
397
398 perl -Mbignum=p,-50 -le 'print sqrt(20)'
399
95a2d02c 400Note that setting precision and accurary at the same time is not possible.
401
126f3c5f 402=item t or trace
403
404This enables a trace mode and is primarily for debugging bignum or
405Math::BigInt/Math::BigFloat.
406
407=item l or lib
408
409Load a different math lib, see L<MATH LIBRARY>.
410
411 perl -Mbignum=l,GMP -e 'print 2 ** 512'
412
413Currently there is no way to specify more than one library on the command
95a2d02c 414line. This means the following does not work:
415
416 perl -Mbignum=l,GMP,Pari -e 'print 2 ** 512'
417
418This will be hopefully fixed soon ;)
126f3c5f 419
d1a15766 420=item hex
421
43cde5e1 422Override the built-in hex() method with a version that can handle big
d1a15766 423integers. Note that under Perl older than v5.9.4, this will be global
424and cannot be disabled with "no bigint;".
425
426=item oct
427
43cde5e1 428Override the built-in oct() method with a version that can handle big
d1a15766 429integers. Note that under Perl older than v5.9.4, this will be global
430and cannot be disabled with "no bigint;".
431
126f3c5f 432=item v or version
433
434This prints out the name and version of all modules used and then exits.
435
b68b7ab1 436 perl -Mbignum=v
126f3c5f 437
95a2d02c 438=back
439
b68b7ab1 440=head2 Methods
b4bc5691 441
442Beside import() and AUTOLOAD() there are only a few other methods.
443
24716a00 444Since all numbers are now objects, you can use all functions that are part of
445the BigInt or BigFloat API. It is wise to use only the bxxx() notation, and not
446the fxxx() notation, though. This makes it possible that the underlying object
447might morph into a different class than BigFloat.
448
4440d13a 449=head2 Caveats
990fb837 450
451But a warning is in order. When using the following to make a copy of a number,
452only a shallow copy will be made.
453
454 $x = 9; $y = $x;
455 $x = $y = 7;
456
b68b7ab1 457If you want to make a real copy, use the following:
458
459 $y = $x->copy();
460
990fb837 461Using the copy or the original with overloaded math is okay, e.g. the
462following work:
463
464 $x = 9; $y = $x;
465 print $x + 1, " ", $y,"\n"; # prints 10 9
466
467but calling any method that modifies the number directly will result in
3c4b39be 468B<both> the original and the copy being destroyed:
990fb837 469
470 $x = 9; $y = $x;
471 print $x->badd(1), " ", $y,"\n"; # prints 10 10
472
473 $x = 9; $y = $x;
474 print $x->binc(1), " ", $y,"\n"; # prints 10 10
475
476 $x = 9; $y = $x;
477 print $x->bmul(2), " ", $y,"\n"; # prints 18 18
478
d1a15766 479Using methods that do not modify, but test the contents works:
990fb837 480
481 $x = 9; $y = $x;
482 $z = 9 if $x->is_zero(); # works fine
483
484See the documentation about the copy constructor and C<=> in overload, as
485well as the documentation in BigInt for further details.
486
b4bc5691 487=over 2
488
489=item inf()
490
3c4b39be 491A shortcut to return Math::BigInt->binf(). Useful because Perl does not always
b4bc5691 492handle bareword C<inf> properly.
493
494=item NaN()
495
3c4b39be 496A shortcut to return Math::BigInt->bnan(). Useful because Perl does not always
b4bc5691 497handle bareword C<NaN> properly.
498
d98d5fa0 499=item e
fade31f0 500
d98d5fa0 501 # perl -Mbignum=e -wle 'print e'
502
503Returns Euler's number C<e>, aka exp(1).
fade31f0 504
505=item PI()
506
d98d5fa0 507 # perl -Mbignum=PI -wle 'print PI'
508
509Returns PI.
510
511=item bexp()
512
513 bexp($power,$accuracy);
514
515Returns Euler's number C<e> raised to the appropriate power, to
516the wanted accuracy.
517
518Example:
519
520 # perl -Mbignum=bexp -wle 'print bexp(1,80)'
521
522=item bpi()
523
524 bpi($accuracy);
525
526Returns PI to the wanted accuracy.
527
528Example:
529
530 # perl -Mbignum=bpi -wle 'print bpi(80)'
fade31f0 531
b4bc5691 532=item upgrade()
533
534Return the class that numbers are upgraded to, is in fact returning
535C<$Math::BigInt::upgrade>.
536
4440d13a 537=item in_effect()
538
539 use bignum;
540
541 print "in effect\n" if bignum::in_effect; # true
542 {
543 no bignum;
544 print "in effect\n" if bignum::in_effect; # false
545 }
546
547Returns true or false if C<bignum> is in effect in the current scope.
548
549This method only works on Perl v5.9.4 or later.
550
b4bc5691 551=back
552
bd49aa09 553=head2 Math Library
126f3c5f 554
555Math with the numbers is done (by default) by a module called
556Math::BigInt::Calc. This is equivalent to saying:
557
558 use bignum lib => 'Calc';
559
560You can change this by using:
561
bd49aa09 562 use bignum lib => 'GMP';
126f3c5f 563
564The following would first try to find Math::BigInt::Foo, then
565Math::BigInt::Bar, and when this also fails, revert to Math::BigInt::Calc:
566
567 use bignum lib => 'Foo,Math::BigInt::Bar';
568
569Please see respective module documentation for further details.
570
bd49aa09 571Using C<lib> warns if none of the specified libraries can be found and
572L<Math::BigInt> did fall back to one of the default libraries.
573To supress this warning, use C<try> instead:
574
575 use bignum try => 'GMP';
576
577If you want the code to die instead of falling back, use C<only> instead:
578
579 use bignum only => 'GMP';
580
126f3c5f 581=head2 INTERNAL FORMAT
582
583The numbers are stored as objects, and their internals might change at anytime,
584especially between math operations. The objects also might belong to different
585classes, like Math::BigInt, or Math::BigFLoat. Mixing them together, even
586with normal scalars is not extraordinary, but normal and expected.
587
588You should not depend on the internal format, all accesses must go through
589accessor methods. E.g. looking at $x->{sign} is not a bright idea since there
590is no guaranty that the object in question has such a hashkey, nor is a hash
591underneath at all.
592
593=head2 SIGN
594
595The sign is either '+', '-', 'NaN', '+inf' or '-inf' and stored seperately.
596You can access it with the sign() method.
597
598A sign of 'NaN' is used to represent the result when input arguments are not
599numbers or as a result of 0/0. '+inf' and '-inf' represent plus respectively
600minus infinity. You will get '+inf' when dividing a positive number by 0, and
601'-inf' when dividing any negative number by 0.
602
d1a15766 603=head1 CAVAETS
604
605=over 2
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
126f3c5f 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)'
bce28014 660 perl -Mbignum -le 'print exp(1)'
126f3c5f 661 perl -Mbignum -le 'print 2 ** 0.5'
662 perl -Mbignum=a,65 -le 'print 2 ** 0.2'
95a2d02c 663 perl -Mbignum=a,65,l,GMP -le 'print 7 ** 7777'
126f3c5f 664
665=head1 LICENSE
666
667This program is free software; you may redistribute it and/or modify it under
668the same terms as Perl itself.
669
670=head1 SEE ALSO
671
672Especially L<bigrat> as in C<perl -Mbigrat -le 'print 1/3+1/4'>.
673
674L<Math::BigFloat>, L<Math::BigInt>, L<Math::BigRat> and L<Math::Big> as well
675as L<Math::BigInt::BitVect>, L<Math::BigInt::Pari> and L<Math::BigInt::GMP>.
676
677=head1 AUTHORS
678
95a2d02c 679(C) by Tels L<http://bloodgate.com/> in early 2002 - 2007.
126f3c5f 680
681=cut