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