This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
Upgrade bignum from version 0.42 to 0.43
[perl5.git] / cpan / bignum / lib / bigrat.pm
CommitLineData
126f3c5f 1package bigrat;
91f07087 2
9de9b613 3use 5.006;
91f07087
SH
4use strict;
5use warnings;
126f3c5f 6
fb7f2fa3 7our $VERSION = '0.43';
91f07087
SH
8
9use Exporter;
10our @ISA = qw( bigint );
11our @EXPORT_OK = qw( PI e bpi bexp hex oct );
12our @EXPORT = qw( inf NaN );
126f3c5f 13
95a2d02c 14use overload;
6aa4fbb5 15use bigint ();
126f3c5f 16
56e812ab 17##############################################################################
126f3c5f 18
56e812ab
PJA
19BEGIN {
20 *inf = \&bigint::inf;
21 *NaN = \&bigint::NaN;
22 *hex = \&bigint::hex;
23 *oct = \&bigint::oct;
24}
d1a15766 25
126f3c5f
JH
26# These are all alike, and thus faked by AUTOLOAD
27
28my @faked = qw/round_mode accuracy precision div_scale/;
91f07087 29our ($AUTOLOAD, $_lite); # _lite for testsuite
56e812ab
PJA
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 *{"bigrat::$name"} =
39 sub {
40 my $self = shift;
41 no strict 'refs';
42 if (defined $_[0]) {
43 Math::BigInt->$name($_[0]);
44 Math::BigFloat->$name($_[0]);
45 return Math::BigRat->$name($_[0]);
46 }
47 return Math::BigInt->$name();
48 };
49 return &$name;
50 }
126f3c5f 51 }
126f3c5f 52
56e812ab
PJA
53 # delayed load of Carp and avoid recursion
54 require Carp;
55 Carp::croak ("Can't call bigrat\-\>$name, not a valid method");
56}
4440d13a 57
56e812ab
PJA
58sub unimport {
59 $^H{bigrat} = undef; # no longer in effect
60 overload::remove_constant('binary', '', 'float', '', 'integer');
61}
62
63sub in_effect {
64 my $level = shift || 0;
65 my $hinthash = (caller($level))[10];
66 $hinthash->{bigrat};
67}
4440d13a 68
d1a15766 69#############################################################################
d1a15766 70
56e812ab
PJA
71sub import {
72 my $self = shift;
126f3c5f 73
56e812ab 74 # see also bignum->import() for additional comments
126f3c5f 75
56e812ab 76 $^H{bigrat} = 1; # we are in effect
4440d13a 77
56e812ab
PJA
78 # for newer Perls always override hex() and oct() with a lexical version:
79 if ($] > 5.009004) {
80 bigint::_override();
d1a15766 81 }
56e812ab
PJA
82 # some defaults
83 my $lib = '';
84 my $lib_kind = 'try';
85 my $upgrade = 'Math::BigFloat';
86
87 my @import = (':constant'); # drive it w/ constant
88 my @a = @_;
89 my $l = scalar @_;
90 my $j = 0;
91 my ($a, $p);
92 my ($ver, $trace); # version? trace?
93 for (my $i = 0; $i < $l ; $i++, $j++) {
94 if ($_[$i] eq 'upgrade') {
95 # this causes upgrading
96 $upgrade = $_[$i + 1]; # or undef to disable
97 my $s = 2;
98 $s = 1 if @a - $j < 2; # avoid "can not modify non-existent..."
99 splice @a, $j, $s;
100 $j -= $s;
101 }
102 elsif ($_[$i] =~ /^(l|lib|try|only)$/) {
103 # this causes a different low lib to take care...
104 $lib_kind = $1;
105 $lib_kind = 'lib' if $lib_kind eq 'l';
106 $lib = $_[$i + 1] || '';
107 my $s = 2;
108 $s = 1 if @a - $j < 2; # avoid "can not modify non-existent..."
109 splice @a, $j, $s;
110 $j -= $s;
111 $i++;
112 }
113 elsif ($_[$i] =~ /^(a|accuracy)$/) {
114 $a = $_[$i + 1];
115 my $s = 2;
116 $s = 1 if @a - $j < 2; # avoid "can not modify non-existent..."
117 splice @a, $j, $s;
118 $j -= $s;
119 $i++;
120 }
121 elsif ($_[$i] =~ /^(p|precision)$/) {
122 $p = $_[$i + 1];
123 my $s = 2;
124 $s = 1 if @a - $j < 2; # avoid "can not modify non-existent..."
125 splice @a, $j, $s;
126 $j -= $s;
127 $i++;
128 }
129 elsif ($_[$i] =~ /^(v|version)$/) {
130 $ver = 1;
131 splice @a, $j, 1;
132 $j--;
133 }
134 elsif ($_[$i] =~ /^(t|trace)$/) {
135 $trace = 1;
136 splice @a, $j, 1;
137 $j--;
138 }
139 elsif ($_[$i] !~ /^(PI|e|bpi|bexp|hex|oct)\z/) {
140 die ("unknown option $_[$i]");
141 }
126f3c5f 142 }
56e812ab
PJA
143 my $class;
144 $_lite = 0; # using M::BI::L ?
145 if ($trace) {
146 require Math::BigInt::Trace;
147 $class = 'Math::BigInt::Trace';
148 $upgrade = 'Math::BigFloat::Trace';
126f3c5f 149 }
56e812ab
PJA
150 else {
151 # see if we can find Math::BigInt::Lite
152 if (!defined $a && !defined $p) { # rounding won't work to well
153 if (eval { require Math::BigInt::Lite; 1 }) {
154 @import = (); # :constant in Lite, not MBI
155 Math::BigInt::Lite->import(':constant');
156 $_lite = 1; # signal okay
157 }
126f3c5f 158 }
56e812ab
PJA
159 require Math::BigInt if $_lite == 0; # not already loaded?
160 $class = 'Math::BigInt'; # regardless of MBIL or not
126f3c5f 161 }
56e812ab
PJA
162 push @import, $lib_kind => $lib if $lib ne '';
163 # Math::BigInt::Trace or plain Math::BigInt
164 $class->import(@import, upgrade => $upgrade);
165
166 require Math::BigFloat;
167 Math::BigFloat->import(upgrade => 'Math::BigRat', ':constant');
168 require Math::BigRat;
169 Math::BigRat->import(@import);
170
171 bigrat->accuracy($a) if defined $a;
172 bigrat->precision($p) if defined $p;
173 if ($ver) {
174 print "bigrat\t\t\t v$VERSION\n";
175 print "Math::BigInt::Lite\t v$Math::BigInt::Lite::VERSION\n" if $_lite;
176 print "Math::BigInt\t\t v$Math::BigInt::VERSION";
177 my $config = Math::BigInt->config();
178 print " lib => $config->{lib} v$config->{lib_version}\n";
179 print "Math::BigFloat\t\t v$Math::BigFloat::VERSION\n";
180 print "Math::BigRat\t\t v$Math::BigRat::VERSION\n";
181 exit;
126f3c5f 182 }
95a2d02c 183
56e812ab
PJA
184 # Take care of octal/hexadecimal constants
185 overload::constant binary =>
186 sub {
187 bigint::_binary_constant(shift);
188 };
95a2d02c 189
56e812ab
PJA
190 # if another big* was already loaded:
191 my ($package) = caller();
4440d13a 192
56e812ab
PJA
193 no strict 'refs';
194 if (!defined *{"${package}::inf"}) {
195 $self->export_to_level(1, $self, @a); # export inf and NaN
4440d13a 196 }
56e812ab 197}
126f3c5f 198
d98d5fa0 199sub PI () { Math::BigFloat->new('3.141592653589793238462643383279502884197'); }
91f07087 200sub e () { Math::BigFloat->new('2.718281828459045235360287471352662497757'); }
d98d5fa0 201
56e812ab
PJA
202sub bpi ($) {
203 local $Math::BigFloat::upgrade;
91f07087 204 Math::BigFloat->bpi(@_);
56e812ab 205}
d98d5fa0 206
56e812ab
PJA
207sub bexp ($$) {
208 local $Math::BigFloat::upgrade;
209 my $x = Math::BigFloat->new($_[0]);
210 $x->bexp($_[1]);
211}
fade31f0 212
126f3c5f
JH
2131;
214
215__END__
216
91f07087
SH
217=pod
218
126f3c5f
JH
219=head1 NAME
220
b1f79218 221bigrat - Transparent BigNumber/BigRational support for Perl
126f3c5f
JH
222
223=head1 SYNOPSIS
224
225 use bigrat;
226
56e812ab
PJA
227 print 2 + 4.5,"\n"; # BigFloat 6.5
228 print 1/3 + 1/4,"\n"; # produces 7/12
126f3c5f 229
4440d13a
T
230 {
231 no bigrat;
56e812ab 232 print 1/3,"\n"; # 0.33333...
4440d13a
T
233 }
234
9663a7f5 235 # Import into current package:
d1a15766
T
236 use bigrat qw/hex oct/;
237 print hex("0x1234567890123490"),"\n";
238 print oct("01234567890123490"),"\n";
239
126f3c5f
JH
240=head1 DESCRIPTION
241
3c4b39be 242All operators (including basic math operations) are overloaded. Integer and
126f3c5f
JH
243floating-point constants are created as proper BigInts or BigFloats,
244respectively.
245
246Other than L<bignum>, this module upgrades to Math::BigRat, meaning that
247instead of 2.5 you will get 2+1/2 as output.
248
b68b7ab1 249=head2 Modules Used
126f3c5f
JH
250
251C<bigrat> is just a thin wrapper around various modules of the Math::BigInt
252family. Think of it as the head of the family, who runs the shop, and orders
253the others to do the work.
254
255The following modules are currently used by bignum:
256
257 Math::BigInt::Lite (for speed, and only if it is loadable)
258 Math::BigInt
259 Math::BigFloat
260 Math::BigRat
261
b68b7ab1 262=head2 Math Library
126f3c5f
JH
263
264Math with the numbers is done (by default) by a module called
265Math::BigInt::Calc. This is equivalent to saying:
266
56e812ab 267 use bigrat lib => 'Calc';
126f3c5f
JH
268
269You can change this by using:
270
bd49aa09 271 use bignum lib => 'GMP';
126f3c5f
JH
272
273The following would first try to find Math::BigInt::Foo, then
274Math::BigInt::Bar, and when this also fails, revert to Math::BigInt::Calc:
275
56e812ab 276 use bigrat lib => 'Foo,Math::BigInt::Bar';
126f3c5f 277
bd49aa09
SP
278Using C<lib> warns if none of the specified libraries can be found and
279L<Math::BigInt> did fall back to one of the default libraries.
c4a6f826 280To suppress this warning, use C<try> instead:
bd49aa09
SP
281
282 use bignum try => 'GMP';
283
284If you want the code to die instead of falling back, use C<only> instead:
285
286 use bignum only => 'GMP';
287
126f3c5f
JH
288Please see respective module documentation for further details.
289
b68b7ab1 290=head2 Sign
126f3c5f 291
b68b7ab1 292The sign is either '+', '-', 'NaN', '+inf' or '-inf'.
126f3c5f
JH
293
294A sign of 'NaN' is used to represent the result when input arguments are not
295numbers or as a result of 0/0. '+inf' and '-inf' represent plus respectively
296minus infinity. You will get '+inf' when dividing a positive number by 0, and
297'-inf' when dividing any negative number by 0.
298
b68b7ab1 299=head2 Methods
126f3c5f
JH
300
301Since all numbers are not objects, you can use all functions that are part of
302the BigInt or BigFloat API. It is wise to use only the bxxx() notation, and not
c4a6f826 303the fxxx() notation, though. This makes you independent on the fact that the
126f3c5f
JH
304underlying object might morph into a different class than BigFloat.
305
95a2d02c
T
306=over 2
307
308=item inf()
309
310A shortcut to return Math::BigInt->binf(). Useful because Perl does not always
311handle bareword C<inf> properly.
312
313=item NaN()
314
315A shortcut to return Math::BigInt->bnan(). Useful because Perl does not always
316handle bareword C<NaN> properly.
317
d98d5fa0
T
318=item e
319
56e812ab 320 # perl -Mbigrat=e -wle 'print e'
d98d5fa0
T
321
322Returns Euler's number C<e>, aka exp(1).
323
324=item PI
325
56e812ab 326 # perl -Mbigrat=PI -wle 'print PI'
d98d5fa0
T
327
328Returns PI.
329
330=item bexp()
331
56e812ab 332 bexp($power,$accuracy);
d98d5fa0
T
333
334Returns Euler's number C<e> raised to the appropriate power, to
335the wanted accuracy.
336
337Example:
338
56e812ab 339 # perl -Mbigrat=bexp -wle 'print bexp(1,80)'
d98d5fa0
T
340
341=item bpi()
342
56e812ab 343 bpi($accuracy);
fade31f0 344
d98d5fa0 345Returns PI to the wanted accuracy.
fade31f0 346
d98d5fa0 347Example:
fade31f0 348
56e812ab 349 # perl -Mbigrat=bpi -wle 'print bpi(80)'
fade31f0 350
95a2d02c
T
351=item upgrade()
352
353Return the class that numbers are upgraded to, is in fact returning
354C<$Math::BigInt::upgrade>.
355
4440d13a
T
356=item in_effect()
357
56e812ab 358 use bigrat;
4440d13a 359
56e812ab
PJA
360 print "in effect\n" if bigrat::in_effect; # true
361 {
362 no bigrat;
363 print "in effect\n" if bigrat::in_effect; # false
364 }
4440d13a
T
365
366Returns true or false if C<bigrat> is in effect in the current scope.
367
368This method only works on Perl v5.9.4 or later.
369
95a2d02c
T
370=back
371
372=head2 MATH LIBRARY
373
374Math with the numbers is done (by default) by a module called
375
c4a6f826 376=head2 Caveat
990fb837
RGS
377
378But a warning is in order. When using the following to make a copy of a number,
379only a shallow copy will be made.
380
381 $x = 9; $y = $x;
382 $x = $y = 7;
383
b68b7ab1
T
384If you want to make a real copy, use the following:
385
56e812ab 386 $y = $x->copy();
b68b7ab1 387
990fb837
RGS
388Using the copy or the original with overloaded math is okay, e.g. the
389following work:
390
391 $x = 9; $y = $x;
392 print $x + 1, " ", $y,"\n"; # prints 10 9
393
394but calling any method that modifies the number directly will result in
3c4b39be 395B<both> the original and the copy being destroyed:
990fb837
RGS
396
397 $x = 9; $y = $x;
398 print $x->badd(1), " ", $y,"\n"; # prints 10 10
399
400 $x = 9; $y = $x;
401 print $x->binc(1), " ", $y,"\n"; # prints 10 10
402
403 $x = 9; $y = $x;
404 print $x->bmul(2), " ", $y,"\n"; # prints 18 18
405
406Using methods that do not modify, but testthe contents works:
407
408 $x = 9; $y = $x;
409 $z = 9 if $x->is_zero(); # works fine
410
411See the documentation about the copy constructor and C<=> in overload, as
412well as the documentation in BigInt for further details.
413
b68b7ab1
T
414=head2 Options
415
416bignum recognizes some options that can be passed while loading it via use.
417The options can (currently) be either a single letter form, or the long form.
418The following options exist:
419
420=over 2
421
422=item a or accuracy
423
424This sets the accuracy for all math operations. The argument must be greater
425than or equal to zero. See Math::BigInt's bround() function for details.
426
56e812ab 427 perl -Mbigrat=a,50 -le 'print sqrt(20)'
b68b7ab1 428
c4a6f826 429Note that setting precision and accuracy at the same time is not possible.
95a2d02c 430
b68b7ab1
T
431=item p or precision
432
433This sets the precision for all math operations. The argument can be any
434integer. Negative values mean a fixed number of digits after the dot, while
435a positive value rounds to this digit left from the dot. 0 or 1 mean round to
436integer. See Math::BigInt's bfround() function for details.
437
56e812ab 438 perl -Mbigrat=p,-50 -le 'print sqrt(20)'
b68b7ab1 439
c4a6f826 440Note that setting precision and accuracy at the same time is not possible.
95a2d02c 441
b68b7ab1
T
442=item t or trace
443
444This enables a trace mode and is primarily for debugging bignum or
445Math::BigInt/Math::BigFloat.
446
447=item l or lib
448
449Load a different math lib, see L<MATH LIBRARY>.
450
56e812ab 451 perl -Mbigrat=l,GMP -e 'print 2 ** 512'
b68b7ab1
T
452
453Currently there is no way to specify more than one library on the command
95a2d02c
T
454line. This means the following does not work:
455
56e812ab 456 perl -Mbignum=l,GMP,Pari -e 'print 2 ** 512'
95a2d02c
T
457
458This will be hopefully fixed soon ;)
b68b7ab1 459
d1a15766
T
460=item hex
461
43cde5e1 462Override the built-in hex() method with a version that can handle big
9663a7f5
FC
463numbers. This overrides it by exporting it to the current package. Under
464Perl v5.10.0 and higher, this is not so necessary, as hex() is lexically
465overridden in the current scope whenever the bigrat pragma is active.
d1a15766
T
466
467=item oct
468
43cde5e1 469Override the built-in oct() method with a version that can handle big
9663a7f5
FC
470numbers. This overrides it by exporting it to the current package. Under
471Perl v5.10.0 and higher, this is not so necessary, as oct() is lexically
472overridden in the current scope whenever the bigrat pragma is active.
d1a15766 473
b68b7ab1
T
474=item v or version
475
476This prints out the name and version of all modules used and then exits.
477
56e812ab 478 perl -Mbigrat=v
b68b7ab1 479
95a2d02c
T
480=back
481
7ed767c4 482=head1 CAVEATS
d1a15766
T
483
484=over 2
485
fa7b7678
TC
486=item Operator vs literal overloading
487
488C<bigrat> works by overloading handling of integer and floating point
489literals, converting them to L<Math::BigInt> or L<Math::BigRat>
490objects.
491
492This means that arithmetic involving only string values or string
493literals will be performed using Perl's built-in operators.
494
495For example:
496
497 use bigrat;
498 my $x = "900000000000000009";
499 my $y = "900000000000000007";
500 print $x - $y;
501
502will output C<0> on default 32-bit builds, since C<bigrat> never sees
503the string literals. To ensure the expression is all treated as
504C<Math::BigInt> or C<Math::BigRat> objects, use a literal number in
505the expression:
506
507 print +(0+$x) - $y;
508
d1a15766
T
509=item in_effect()
510
511This method only works on Perl v5.9.4 or later.
512
513=item hex()/oct()
514
515C<bigint> overrides these routines with versions that can also handle
516big integer values. Under Perl prior to version v5.9.4, however, this
517will not happen unless you specifically ask for it with the two
518import tags "hex" and "oct" - and then it will be global and cannot be
519disabled inside a scope with "no bigint":
520
56e812ab 521 use bigint qw/hex oct/;
d1a15766 522
56e812ab
PJA
523 print hex("0x1234567890123456");
524 {
525 no bigint;
526 print hex("0x1234567890123456");
527 }
d1a15766
T
528
529The second call to hex() will warn about a non-portable constant.
530
531Compare this to:
532
56e812ab 533 use bigint;
d1a15766 534
56e812ab
PJA
535 # will warn only under Perl older than v5.9.4
536 print hex("0x1234567890123456");
d1a15766
T
537
538=back
539
126f3c5f 540=head1 EXAMPLES
bcb1dae1 541
56e812ab
PJA
542 perl -Mbigrat -le 'print sqrt(33)'
543 perl -Mbigrat -le 'print 2*255'
544 perl -Mbigrat -le 'print 4.5+2*255'
545 perl -Mbigrat -le 'print 3/7 + 5/7 + 8/3'
546 perl -Mbigrat -le 'print 12->is_odd()';
547 perl -Mbignum=l,GMP -le 'print 7 ** 7777'
126f3c5f
JH
548
549=head1 LICENSE
550
551This program is free software; you may redistribute it and/or modify it under
552the same terms as Perl itself.
553
554=head1 SEE ALSO
555
556Especially L<bignum>.
557
558L<Math::BigFloat>, L<Math::BigInt>, L<Math::BigRat> and L<Math::Big> as well
e0f4a93e 559as L<Math::BigInt::Pari> and L<Math::BigInt::GMP>.
126f3c5f
JH
560
561=head1 AUTHORS
562
95a2d02c 563(C) by Tels L<http://bloodgate.com/> in early 2002 - 2007.
126f3c5f
JH
564
565=cut