This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
EBCDIC fixes for gzip
[perl5.git] / lib / bigint.pm
CommitLineData
126f3c5f 1package bigint;
95a2d02c 2use 5.006002;
126f3c5f 3
4440d13a 4$VERSION = '0.22';
126f3c5f 5use Exporter;
b4bc5691
T
6@ISA = qw( Exporter );
7@EXPORT_OK = qw( );
8@EXPORT = qw( inf NaN );
126f3c5f
JH
9
10use strict;
11use overload;
12
13##############################################################################
14
15# These are all alike, and thus faked by AUTOLOAD
16
17my @faked = qw/round_mode accuracy precision div_scale/;
18use vars qw/$VERSION $AUTOLOAD $_lite/; # _lite for testsuite
19
20sub 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 {
990fb837 36 return Math::BigInt->$name($_[0]);
126f3c5f
JH
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
49sub upgrade
50 {
95a2d02c 51 $Math::BigInt::upgrade;
126f3c5f
JH
52 }
53
95a2d02c
T
54sub _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
67sub _float_constant
126f3c5f
JH
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 }
9b924220 83 my ($mis,$miv,$mfv,$es,$ev) = Math::BigInt::_split($float);
126f3c5f
JH
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);
95a2d02c 104 $sign.$$miv.$mfv; # 123.45e+1 => 1234
126f3c5f
JH
105 }
106
4440d13a
T
107sub unimport
108 {
109 $^H{bigint} = undef; # no longer in effect
110 overload::remove_constant('binary','','float','','integer');
111 }
112
113sub in_effect
114 {
115 my $level = shift || 0;
116 my $hinthash = (caller($level))[10];
117 $hinthash->{bigint};
118 }
119
126f3c5f
JH
120sub import
121 {
122 my $self = shift;
123
4440d13a
T
124 $^H{bigint} = 1; # we are in effect
125
126f3c5f 126 # some defaults
bd49aa09 127 my $lib = ''; my $lib_kind = 'try';
126f3c5f
JH
128
129 my @import = ( ':constant' ); # drive it w/ constant
130 my @a = @_; my $l = scalar @_; my $j = 0;
131 my ($ver,$trace); # version? trace?
132 my ($a,$p); # accuracy, precision
133 for ( my $i = 0; $i < $l ; $i++,$j++ )
134 {
bd49aa09 135 if ($_[$i] =~ /^(l|lib|try|only)$/)
126f3c5f
JH
136 {
137 # this causes a different low lib to take care...
bd49aa09 138 $lib_kind = $1; $lib_kind = 'lib' if $lib_kind eq 'l';
126f3c5f
JH
139 $lib = $_[$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] =~ /^(a|accuracy)$/)
144 {
145 $a = $_[$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] =~ /^(p|precision)$/)
150 {
151 $p = $_[$i+1];
152 my $s = 2; $s = 1 if @a-$j < 2; # avoid "can not modify non-existant..."
153 splice @a, $j, $s; $j -= $s; $i++;
154 }
155 elsif ($_[$i] =~ /^(v|version)$/)
156 {
157 $ver = 1;
158 splice @a, $j, 1; $j --;
159 }
160 elsif ($_[$i] =~ /^(t|trace)$/)
161 {
162 $trace = 1;
163 splice @a, $j, 1; $j --;
164 }
165 else { die "unknown option $_[$i]"; }
166 }
167 my $class;
168 $_lite = 0; # using M::BI::L ?
169 if ($trace)
170 {
171 require Math::BigInt::Trace; $class = 'Math::BigInt::Trace';
126f3c5f
JH
172 }
173 else
174 {
175 # see if we can find Math::BigInt::Lite
176 if (!defined $a && !defined $p) # rounding won't work to well
177 {
178 eval 'require Math::BigInt::Lite;';
179 if ($@ eq '')
180 {
181 @import = ( ); # :constant in Lite, not MBI
182 Math::BigInt::Lite->import( ':constant' );
183 $_lite= 1; # signal okay
184 }
185 }
186 require Math::BigInt if $_lite == 0; # not already loaded?
187 $class = 'Math::BigInt'; # regardless of MBIL or not
233f7bc0 188 }
bd49aa09 189 push @import, $lib_kind => $lib if $lib ne '';
126f3c5f 190 # Math::BigInt::Trace or plain Math::BigInt
233f7bc0 191 $class->import(@import);
126f3c5f
JH
192
193 bigint->accuracy($a) if defined $a;
194 bigint->precision($p) if defined $p;
195 if ($ver)
196 {
197 print "bigint\t\t\t v$VERSION\n";
198 print "Math::BigInt::Lite\t v$Math::BigInt::Lite::VERSION\n" if $_lite;
199 print "Math::BigInt\t\t v$Math::BigInt::VERSION";
200 my $config = Math::BigInt->config();
201 print " lib => $config->{lib} v$config->{lib_version}\n";
202 exit;
203 }
204 # we take care of floating point constants, since BigFloat isn't available
205 # and BigInt doesn't like them:
95a2d02c
T
206 overload::constant float => sub { Math::BigInt->new( _float_constant(shift) ); };
207 # Take care of octal/hexadecimal constants
208 overload::constant binary => sub { _binary_constant(shift) };
b4bc5691 209
4440d13a
T
210 # if another big* was already loaded:
211 my ($package) = caller();
212
213 no strict 'refs';
214 if (!defined *{"${package}::inf"})
215 {
216 $self->export_to_level(1,$self,@a); # export inf and NaN
217 }
126f3c5f
JH
218 }
219
b4bc5691
T
220sub inf () { Math::BigInt->binf(); }
221sub NaN () { Math::BigInt->bnan(); }
222
126f3c5f
JH
2231;
224
225__END__
226
227=head1 NAME
228
b4bc5691 229bigint - Transparent BigInteger support for Perl
126f3c5f
JH
230
231=head1 SYNOPSIS
232
f9156151 233 use bigint;
126f3c5f
JH
234
235 $x = 2 + 4.5,"\n"; # BigInt 6
b4bc5691
T
236 print 2 ** 512,"\n"; # really is what you think it is
237 print inf + 42,"\n"; # inf
238 print NaN * 7,"\n"; # NaN
126f3c5f 239
4440d13a
T
240 {
241 no bigint;
242 print 2 ** 256,"\n"; # a normal Perl scalar now
243 }
244
126f3c5f
JH
245=head1 DESCRIPTION
246
247All operators (including basic math operations) are overloaded. Integer
248constants are created as proper BigInts.
249
1ad2138d
T
250Floating point constants are truncated to integer. All parts and results of
251expressions are also truncated.
252
253Unlike L<integer>, this pragma creates integer constants that are only
254limited in their size by the available memory and CPU time.
255
256=head2 use integer vs. use bigint
257
258There is one small difference between C<use integer> and C<use bigint>: the
259former will not affect assignments to variables and the return value of
260some functions. C<bigint> truncates these results to integer too:
261
262 # perl -Minteger -wle 'print 3.2'
263 3.2
264 # perl -Minteger -wle 'print 3.2 + 0'
265 3
266 # perl -Mbigint -wle 'print 3.2'
267 3
268 # perl -Mbigint -wle 'print 3.2 + 0'
269 3
270
271 # perl -Mbigint -wle 'print exp(1) + 0'
272 2
273 # perl -Mbigint -wle 'print exp(1)'
274 2
275 # perl -Mbigint -wle 'print exp(1)'
276 2.71828182845905
277 # perl -Mbigint -wle 'print exp(1) + 0'
278 2
279
280In practice this makes seldom a difference as B<parts and results> of
281expressions will be truncated anyway, but this can, for instance, affect the
282return value of subroutines:
283
284 sub three_integer { use integer; return 3.2; }
285 sub three_bigint { use bigint; return 3.2; }
286
287 print three_integer(), " ", three_bigint(),"\n"; # prints "3.2 3"
126f3c5f 288
b68b7ab1 289=head2 Options
126f3c5f
JH
290
291bigint recognizes some options that can be passed while loading it via use.
292The options can (currently) be either a single letter form, or the long form.
293The following options exist:
294
295=over 2
296
297=item a or accuracy
298
299This sets the accuracy for all math operations. The argument must be greater
300than or equal to zero. See Math::BigInt's bround() function for details.
301
302 perl -Mbigint=a,2 -le 'print 12345+1'
303
95a2d02c
T
304Note that setting precision and accurary at the same time is not possible.
305
126f3c5f
JH
306=item p or precision
307
308This sets the precision for all math operations. The argument can be any
309integer. Negative values mean a fixed number of digits after the dot, and
310are <B>ignored</B> since all operations happen in integer space.
311A positive value rounds to this digit left from the dot. 0 or 1 mean round to
312integer and are ignore like negative values.
313
314See Math::BigInt's bfround() function for details.
315
316 perl -Mbignum=p,5 -le 'print 123456789+123'
317
95a2d02c
T
318Note that setting precision and accurary at the same time is not possible.
319
126f3c5f
JH
320=item t or trace
321
322This enables a trace mode and is primarily for debugging bigint or
323Math::BigInt.
324
bd49aa09 325=item l, lib, try or only
126f3c5f 326
bd49aa09 327Load a different math lib, see L<Math Library>.
126f3c5f 328
bd49aa09
SP
329 perl -Mbigint=lib,GMP -e 'print 2 ** 512'
330 perl -Mbigint=try,GMP -e 'print 2 ** 512'
331 perl -Mbigint=only,GMP -e 'print 2 ** 512'
126f3c5f
JH
332
333Currently there is no way to specify more than one library on the command
95a2d02c
T
334line. This means the following does not work:
335
336 perl -Mbignum=l,GMP,Pari -e 'print 2 ** 512'
337
338This will be hopefully fixed soon ;)
126f3c5f
JH
339
340=item v or version
341
342This prints out the name and version of all modules used and then exits.
343
b68b7ab1 344 perl -Mbigint=v
126f3c5f 345
95a2d02c
T
346=back
347
b68b7ab1 348=head2 Math Library
126f3c5f
JH
349
350Math with the numbers is done (by default) by a module called
351Math::BigInt::Calc. This is equivalent to saying:
352
353 use bigint lib => 'Calc';
354
355You can change this by using:
356
bd49aa09 357 use bignum lib => 'GMP';
126f3c5f
JH
358
359The following would first try to find Math::BigInt::Foo, then
360Math::BigInt::Bar, and when this also fails, revert to Math::BigInt::Calc:
361
362 use bigint lib => 'Foo,Math::BigInt::Bar';
363
bd49aa09
SP
364Using C<lib> warns if none of the specified libraries can be found and
365L<Math::BigInt> did fall back to one of the default libraries.
366To supress this warning, use C<try> instead:
367
368 use bignum try => 'GMP';
369
370If you want the code to die instead of falling back, use C<only> instead:
371
372 use bignum only => 'GMP';
373
126f3c5f
JH
374Please see respective module documentation for further details.
375
b68b7ab1 376=head2 Internal Format
126f3c5f
JH
377
378The numbers are stored as objects, and their internals might change at anytime,
379especially between math operations. The objects also might belong to different
380classes, like Math::BigInt, or Math::BigInt::Lite. Mixing them together, even
381with normal scalars is not extraordinary, but normal and expected.
382
383You should not depend on the internal format, all accesses must go through
990fb837 384accessor methods. E.g. looking at $x->{sign} is not a good idea since there
126f3c5f
JH
385is no guaranty that the object in question has such a hash key, nor is a hash
386underneath at all.
387
b68b7ab1 388=head2 Sign
126f3c5f 389
b68b7ab1 390The sign is either '+', '-', 'NaN', '+inf' or '-inf'.
126f3c5f
JH
391You can access it with the sign() method.
392
393A sign of 'NaN' is used to represent the result when input arguments are not
394numbers or as a result of 0/0. '+inf' and '-inf' represent plus respectively
395minus infinity. You will get '+inf' when dividing a positive number by 0, and
396'-inf' when dividing any negative number by 0.
397
b68b7ab1 398=head2 Methods
126f3c5f
JH
399
400Since all numbers are now objects, you can use all functions that are part of
401the BigInt API. You can only use the bxxx() notation, and not the fxxx()
402notation, though.
403
95a2d02c
T
404=over 2
405
406=item inf()
407
408A shortcut to return Math::BigInt->binf(). Useful because Perl does not always
409handle bareword C<inf> properly.
410
411=item NaN()
412
413A shortcut to return Math::BigInt->bnan(). Useful because Perl does not always
414handle bareword C<NaN> properly.
415
416=item upgrade()
417
418Return the class that numbers are upgraded to, is in fact returning
419C<$Math::BigInt::upgrade>.
420
4440d13a
T
421=item in_effect()
422
423 use bigint;
424
425 print "in effect\n" if bigint::in_effect; # true
426 {
427 no bigint;
428 print "in effect\n" if bigint::in_effect; # false
429 }
430
431Returns true or false if C<bigint> is in effect in the current scope.
432
433This method only works on Perl v5.9.4 or later.
434
95a2d02c
T
435=back
436
437=head2 MATH LIBRARY
438
439Math with the numbers is done (by default) by a module called
440
b68b7ab1 441=head2 Caveat
990fb837
RGS
442
443But a warning is in order. When using the following to make a copy of a number,
444only a shallow copy will be made.
445
446 $x = 9; $y = $x;
447 $x = $y = 7;
448
449Using the copy or the original with overloaded math is okay, e.g. the
450following work:
451
452 $x = 9; $y = $x;
453 print $x + 1, " ", $y,"\n"; # prints 10 9
454
455but calling any method that modifies the number directly will result in
3c4b39be 456B<both> the original and the copy being destroyed:
990fb837
RGS
457
458 $x = 9; $y = $x;
459 print $x->badd(1), " ", $y,"\n"; # prints 10 10
460
461 $x = 9; $y = $x;
462 print $x->binc(1), " ", $y,"\n"; # prints 10 10
463
464 $x = 9; $y = $x;
465 print $x->bmul(2), " ", $y,"\n"; # prints 18 18
466
467Using methods that do not modify, but testthe contents works:
468
469 $x = 9; $y = $x;
470 $z = 9 if $x->is_zero(); # works fine
471
472See the documentation about the copy constructor and C<=> in overload, as
473well as the documentation in BigInt for further details.
474
126f3c5f
JH
475=head1 MODULES USED
476
477C<bigint> is just a thin wrapper around various modules of the Math::BigInt
478family. Think of it as the head of the family, who runs the shop, and orders
479the others to do the work.
480
481The following modules are currently used by bigint:
482
483 Math::BigInt::Lite (for speed, and only if it is loadable)
484 Math::BigInt
485
486=head1 EXAMPLES
487
488Some cool command line examples to impress the Python crowd ;) You might want
489to compare them to the results under -Mbignum or -Mbigrat:
490
491 perl -Mbigint -le 'print sqrt(33)'
492 perl -Mbigint -le 'print 2*255'
493 perl -Mbigint -le 'print 4.5+2*255'
494 perl -Mbigint -le 'print 3/7 + 5/7 + 8/3'
495 perl -Mbigint -le 'print 123->is_odd()'
496 perl -Mbigint -le 'print log(2)'
497 perl -Mbigint -le 'print 2 ** 0.5'
498 perl -Mbigint=a,65 -le 'print 2 ** 0.2'
95a2d02c 499 perl -Mbignum=a,65,l,GMP -le 'print 7 ** 7777'
126f3c5f
JH
500
501=head1 LICENSE
502
503This program is free software; you may redistribute it and/or modify it under
504the same terms as Perl itself.
505
506=head1 SEE ALSO
507
508Especially L<bigrat> as in C<perl -Mbigrat -le 'print 1/3+1/4'> and
509L<bignum> as in C<perl -Mbignum -le 'print sqrt(2)'>.
510
511L<Math::BigInt>, L<Math::BigRat> and L<Math::Big> as well
512as L<Math::BigInt::BitVect>, L<Math::BigInt::Pari> and L<Math::BigInt::GMP>.
513
514=head1 AUTHORS
515
95a2d02c 516(C) by Tels L<http://bloodgate.com/> in early 2002 - 2007.
126f3c5f
JH
517
518=cut