1Math::BigFloat(3pm) Perl Programmers Reference Guide Math::BigFloat(3pm)
2
3
4
6 Math::BigFloat - Arbitrary size floating point math package
7
9 use Math::BigFloat;
10
11 # Number creation
12 my $x = Math::BigFloat->new($str); # defaults to 0
13 my $y = $x->copy(); # make a true copy
14 my $nan = Math::BigFloat->bnan(); # create a NotANumber
15 my $zero = Math::BigFloat->bzero(); # create a +0
16 my $inf = Math::BigFloat->binf(); # create a +inf
17 my $inf = Math::BigFloat->binf('-'); # create a -inf
18 my $one = Math::BigFloat->bone(); # create a +1
19 my $mone = Math::BigFloat->bone('-'); # create a -1
20
21 my $pi = Math::BigFloat->bpi(100); # PI to 100 digits
22
23 # the following examples compute their result to 100 digits accuracy:
24 my $cos = Math::BigFloat->new(1)->bcos(100); # cosinus(1)
25 my $sin = Math::BigFloat->new(1)->bsin(100); # sinus(1)
26 my $atan = Math::BigFloat->new(1)->batan(100); # arcus tangens(1)
27
28 my $atan2 = Math::BigFloat->new( 1 )->batan2( 1 ,100); # batan(1)
29 my $atan2 = Math::BigFloat->new( 1 )->batan2( 8 ,100); # batan(1/8)
30 my $atan2 = Math::BigFloat->new( -2 )->batan2( 1 ,100); # batan(-2)
31
32 # Testing
33 $x->is_zero(); # true if arg is +0
34 $x->is_nan(); # true if arg is NaN
35 $x->is_one(); # true if arg is +1
36 $x->is_one('-'); # true if arg is -1
37 $x->is_odd(); # true if odd, false for even
38 $x->is_even(); # true if even, false for odd
39 $x->is_pos(); # true if >= 0
40 $x->is_neg(); # true if < 0
41 $x->is_inf(sign); # true if +inf, or -inf (default is '+')
42
43 $x->bcmp($y); # compare numbers (undef,<0,=0,>0)
44 $x->bacmp($y); # compare absolutely (undef,<0,=0,>0)
45 $x->sign(); # return the sign, either +,- or NaN
46 $x->digit($n); # return the nth digit, counting from right
47 $x->digit(-$n); # return the nth digit, counting from left
48
49 # The following all modify their first argument. If you want to preserve
50 # $x, use $z = $x->copy()->bXXX($y); See under L<CAVEATS> for why this is
51 # necessary when mixing $a = $b assignments with non-overloaded math.
52
53 # set
54 $x->bzero(); # set $i to 0
55 $x->bnan(); # set $i to NaN
56 $x->bone(); # set $x to +1
57 $x->bone('-'); # set $x to -1
58 $x->binf(); # set $x to inf
59 $x->binf('-'); # set $x to -inf
60
61 $x->bneg(); # negation
62 $x->babs(); # absolute value
63 $x->bnorm(); # normalize (no-op)
64 $x->bnot(); # two's complement (bit wise not)
65 $x->binc(); # increment x by 1
66 $x->bdec(); # decrement x by 1
67
68 $x->badd($y); # addition (add $y to $x)
69 $x->bsub($y); # subtraction (subtract $y from $x)
70 $x->bmul($y); # multiplication (multiply $x by $y)
71 $x->bdiv($y); # divide, set $x to quotient
72 # return (quo,rem) or quo if scalar
73
74 $x->bmod($y); # modulus ($x % $y)
75 $x->bpow($y); # power of arguments ($x ** $y)
76 $x->bmodpow($exp,$mod); # modular exponentation (($num**$exp) % $mod))
77 $x->blsft($y, $n); # left shift by $y places in base $n
78 $x->brsft($y, $n); # right shift by $y places in base $n
79 # returns (quo,rem) or quo if in scalar context
80
81 $x->blog(); # logarithm of $x to base e (Euler's number)
82 $x->blog($base); # logarithm of $x to base $base (f.i. 2)
83 $x->bexp(); # calculate e ** $x where e is Euler's number
84
85 $x->band($y); # bit-wise and
86 $x->bior($y); # bit-wise inclusive or
87 $x->bxor($y); # bit-wise exclusive or
88 $x->bnot(); # bit-wise not (two's complement)
89
90 $x->bsqrt(); # calculate square-root
91 $x->broot($y); # $y'th root of $x (e.g. $y == 3 => cubic root)
92 $x->bfac(); # factorial of $x (1*2*3*4*..$x)
93
94 $x->bround($N); # accuracy: preserve $N digits
95 $x->bfround($N); # precision: round to the $Nth digit
96
97 $x->bfloor(); # return integer less or equal than $x
98 $x->bceil(); # return integer greater or equal than $x
99
100 # The following do not modify their arguments:
101
102 bgcd(@values); # greatest common divisor
103 blcm(@values); # lowest common multiplicator
104
105 $x->bstr(); # return string
106 $x->bsstr(); # return string in scientific notation
107
108 $x->as_int(); # return $x as BigInt
109 $x->exponent(); # return exponent as BigInt
110 $x->mantissa(); # return mantissa as BigInt
111 $x->parts(); # return (mantissa,exponent) as BigInt
112
113 $x->length(); # number of digits (w/o sign and '.')
114 ($l,$f) = $x->length(); # number of digits, and length of fraction
115
116 $x->precision(); # return P of $x (or global, if P of $x undef)
117 $x->precision($n); # set P of $x to $n
118 $x->accuracy(); # return A of $x (or global, if A of $x undef)
119 $x->accuracy($n); # set A $x to $n
120
121 # these get/set the appropriate global value for all BigFloat objects
122 Math::BigFloat->precision(); # Precision
123 Math::BigFloat->accuracy(); # Accuracy
124 Math::BigFloat->round_mode(); # rounding mode
125
127 All operators (including basic math operations) are overloaded if you
128 declare your big floating point numbers as
129
130 $i = new Math::BigFloat '12_3.456_789_123_456_789E-2';
131
132 Operations with overloaded operators preserve the arguments, which is
133 exactly what you expect.
134
135 Canonical notation
136 Input to these routines are either BigFloat objects, or strings of the
137 following four forms:
138
139 · "/^[+-]\d+$/"
140
141 · "/^[+-]\d+\.\d*$/"
142
143 · "/^[+-]\d+E[+-]?\d+$/"
144
145 · "/^[+-]\d*\.\d+E[+-]?\d+$/"
146
147 all with optional leading and trailing zeros and/or spaces.
148 Additionally, numbers are allowed to have an underscore between any two
149 digits.
150
151 Empty strings as well as other illegal numbers results in 'NaN'.
152
153 bnorm() on a BigFloat object is now effectively a no-op, since the
154 numbers are always stored in normalized form. On a string, it creates a
155 BigFloat object.
156
157 Output
158 Output values are BigFloat objects (normalized), except for bstr() and
159 bsstr().
160
161 The string output will always have leading and trailing zeros stripped
162 and drop a plus sign. "bstr()" will give you always the form with a
163 decimal point, while "bsstr()" (s for scientific) gives you the
164 scientific notation.
165
166 Input bstr() bsstr()
167 '-0' '0' '0E1'
168 ' -123 123 123' '-123123123' '-123123123E0'
169 '00.0123' '0.0123' '123E-4'
170 '123.45E-2' '1.2345' '12345E-4'
171 '10E+3' '10000' '1E4'
172
173 Some routines ("is_odd()", "is_even()", "is_zero()", "is_one()",
174 "is_nan()") return true or false, while others ("bcmp()", "bacmp()")
175 return either undef, <0, 0 or >0 and are suited for sort.
176
177 Actual math is done by using the class defined with "with =" Class;>
178 (which defaults to BigInts) to represent the mantissa and exponent.
179
180 The sign "/^[+-]$/" is stored separately. The string 'NaN' is used to
181 represent the result when input arguments are not numbers, as well as
182 the result of dividing by zero.
183
184 "mantissa()", "exponent()" and "parts()"
185 "mantissa()" and "exponent()" return the said parts of the BigFloat as
186 BigInts such that:
187
188 $m = $x->mantissa();
189 $e = $x->exponent();
190 $y = $m * ( 10 ** $e );
191 print "ok\n" if $x == $y;
192
193 "($m,$e) = $x->parts();" is just a shortcut giving you both of them.
194
195 A zero is represented and returned as 0E1, not 0E0 (after Knuth).
196
197 Currently the mantissa is reduced as much as possible, favouring higher
198 exponents over lower ones (e.g. returning 1e7 instead of 10e6 or
199 10000000e0). This might change in the future, so do not depend on it.
200
201 Accuracy vs. Precision
202 See also: Rounding.
203
204 Math::BigFloat supports both precision (rounding to a certain place
205 before or after the dot) and accuracy (rounding to a certain number of
206 digits). For a full documentation, examples and tips on these topics
207 please see the large section about rounding in Math::BigInt.
208
209 Since things like sqrt(2) or "1 / 3" must presented with a limited
210 accuracy lest a operation consumes all resources, each operation
211 produces no more than the requested number of digits.
212
213 If there is no gloabl precision or accuracy set, and the operation in
214 question was not called with a requested precision or accuracy, and the
215 input $x has no accuracy or precision set, then a fallback parameter
216 will be used. For historical reasons, it is called "div_scale" and can
217 be accessed via:
218
219 $d = Math::BigFloat->div_scale(); # query
220 Math::BigFloat->div_scale($n); # set to $n digits
221
222 The default value for "div_scale" is 40.
223
224 In case the result of one operation has more digits than specified, it
225 is rounded. The rounding mode taken is either the default mode, or the
226 one supplied to the operation after the scale:
227
228 $x = Math::BigFloat->new(2);
229 Math::BigFloat->accuracy(5); # 5 digits max
230 $y = $x->copy()->bdiv(3); # will give 0.66667
231 $y = $x->copy()->bdiv(3,6); # will give 0.666667
232 $y = $x->copy()->bdiv(3,6,undef,'odd'); # will give 0.666667
233 Math::BigFloat->round_mode('zero');
234 $y = $x->copy()->bdiv(3,6); # will also give 0.666667
235
236 Note that "Math::BigFloat->accuracy()" and
237 "Math::BigFloat->precision()" set the global variables, and thus any
238 newly created number will be subject to the global rounding
239 immediately. This means that in the examples above, the 3 as argument
240 to "bdiv()" will also get an accuracy of 5.
241
242 It is less confusing to either calculate the result fully, and
243 afterwards round it explicitly, or use the additional parameters to the
244 math functions like so:
245
246 use Math::BigFloat;
247 $x = Math::BigFloat->new(2);
248 $y = $x->copy()->bdiv(3);
249 print $y->bround(5),"\n"; # will give 0.66667
250
251 or
252
253 use Math::BigFloat;
254 $x = Math::BigFloat->new(2);
255 $y = $x->copy()->bdiv(3,5); # will give 0.66667
256 print "$y\n";
257
258 Rounding
259 ffround ( +$scale )
260 Rounds to the $scale'th place left from the '.', counting from the
261 dot. The first digit is numbered 1.
262
263 ffround ( -$scale )
264 Rounds to the $scale'th place right from the '.', counting from the
265 dot.
266
267 ffround ( 0 )
268 Rounds to an integer.
269
270 fround ( +$scale )
271 Preserves accuracy to $scale digits from the left (aka significant
272 digits) and pads the rest with zeros. If the number is between 1 and
273 -1, the significant digits count from the first non-zero after the
274 '.'
275
276 fround ( -$scale ) and fround ( 0 )
277 These are effectively no-ops.
278
279 All rounding functions take as a second parameter a rounding mode from
280 one of the following: 'even', 'odd', '+inf', '-inf', 'zero', 'trunc' or
281 'common'.
282
283 The default rounding mode is 'even'. By using
284 "Math::BigFloat->round_mode($round_mode);" you can get and set the
285 default mode for subsequent rounding. The usage of
286 "$Math::BigFloat::$round_mode" is no longer supported. The second
287 parameter to the round functions then overrides the default
288 temporarily.
289
290 The "as_number()" function returns a BigInt from a Math::BigFloat. It
291 uses 'trunc' as rounding mode to make it equivalent to:
292
293 $x = 2.5;
294 $y = int($x) + 2;
295
296 You can override this by passing the desired rounding mode as parameter
297 to "as_number()":
298
299 $x = Math::BigFloat->new(2.5);
300 $y = $x->as_number('odd'); # $y = 3
301
303 Math::BigFloat supports all methods that Math::BigInt supports, except
304 it calculates non-integer results when possible. Please see
305 Math::BigInt for a full description of each method. Below are just the
306 most important differences:
307
308 accuracy
309 $x->accuracy(5); # local for $x
310 CLASS->accuracy(5); # global for all members of CLASS
311 # Note: This also applies to new()!
312
313 $A = $x->accuracy(); # read out accuracy that affects $x
314 $A = CLASS->accuracy(); # read out global accuracy
315
316 Set or get the global or local accuracy, aka how many significant
317 digits the results have. If you set a global accuracy, then this also
318 applies to new()!
319
320 Warning! The accuracy sticks, e.g. once you created a number under the
321 influence of "CLASS->accuracy($A)", all results from math operations
322 with that number will also be rounded.
323
324 In most cases, you should probably round the results explicitly using
325 one of round(), bround() or bfround() or by passing the desired
326 accuracy to the math operation as additional parameter:
327
328 my $x = Math::BigInt->new(30000);
329 my $y = Math::BigInt->new(7);
330 print scalar $x->copy()->bdiv($y, 2); # print 4300
331 print scalar $x->copy()->bdiv($y)->bround(2); # print 4300
332
333 precision()
334 $x->precision(-2); # local for $x, round at the second digit right of the dot
335 $x->precision(2); # ditto, round at the second digit left of the dot
336
337 CLASS->precision(5); # Global for all members of CLASS
338 # This also applies to new()!
339 CLASS->precision(-5); # ditto
340
341 $P = CLASS->precision(); # read out global precision
342 $P = $x->precision(); # read out precision that affects $x
343
344 Note: You probably want to use accuracy() instead. With accuracy you
345 set the number of digits each result should have, with precision you
346 set the place where to round!
347
348 bexp()
349 $x->bexp($accuracy); # calculate e ** X
350
351 Calculates the expression "e ** $x" where "e" is Euler's number.
352
353 This method was added in v1.82 of Math::BigInt (April 2007).
354
355 bnok()
356 $x->bnok($y); # x over y (binomial coefficient n over k)
357
358 Calculates the binomial coefficient n over k, also called the "choose"
359 function. The result is equivalent to:
360
361 ( n ) n!
362 | - | = -------
363 ( k ) k!(n-k)!
364
365 This method was added in v1.84 of Math::BigInt (April 2007).
366
367 bpi()
368 print Math::BigFloat->bpi(100), "\n";
369
370 Calculate PI to N digits (including the 3 before the dot). The result
371 is rounded according to the current rounding mode, which defaults to
372 "even".
373
374 This method was added in v1.87 of Math::BigInt (June 2007).
375
376 bcos()
377 my $x = Math::BigFloat->new(1);
378 print $x->bcos(100), "\n";
379
380 Calculate the cosinus of $x, modifying $x in place.
381
382 This method was added in v1.87 of Math::BigInt (June 2007).
383
384 bsin()
385 my $x = Math::BigFloat->new(1);
386 print $x->bsin(100), "\n";
387
388 Calculate the sinus of $x, modifying $x in place.
389
390 This method was added in v1.87 of Math::BigInt (June 2007).
391
392 batan2()
393 my $y = Math::BigFloat->new(2);
394 my $x = Math::BigFloat->new(3);
395 print $y->batan2($x), "\n";
396
397 Calculate the arcus tanges of $y divided by $x, modifying $y in place.
398 See also batan().
399
400 This method was added in v1.87 of Math::BigInt (June 2007).
401
402 batan()
403 my $x = Math::BigFloat->new(1);
404 print $x->batan(100), "\n";
405
406 Calculate the arcus tanges of $x, modifying $x in place. See also
407 batan2().
408
409 This method was added in v1.87 of Math::BigInt (June 2007).
410
411 bmuladd()
412 $x->bmuladd($y,$z);
413
414 Multiply $x by $y, and then add $z to the result.
415
416 This method was added in v1.87 of Math::BigInt (June 2007).
417
419 After "use Math::BigFloat ':constant'" all the floating point constants
420 in the given scope are converted to "Math::BigFloat". This conversion
421 happens at compile time.
422
423 In particular
424
425 perl -MMath::BigFloat=:constant -e 'print 2E-100,"\n"'
426
427 prints the value of "2E-100". Note that without conversion of constants
428 the expression 2E-100 will be calculated as normal floating point
429 number.
430
431 Please note that ':constant' does not affect integer constants, nor
432 binary nor hexadecimal constants. Use bignum or Math::BigInt to get
433 this to work.
434
435 Math library
436 Math with the numbers is done (by default) by a module called
437 Math::BigInt::Calc. This is equivalent to saying:
438
439 use Math::BigFloat lib => 'Calc';
440
441 You can change this by using:
442
443 use Math::BigFloat lib => 'GMP';
444
445 Note: General purpose packages should not be explicit about the library
446 to use; let the script author decide which is best.
447
448 Note: The keyword 'lib' will warn when the requested library could not
449 be loaded. To suppress the warning use 'try' instead:
450
451 use Math::BigFloat try => 'GMP';
452
453 If your script works with huge numbers and Calc is too slow for them,
454 you can also for the loading of one of these libraries and if none of
455 them can be used, the code will die:
456
457 use Math::BigFloat only => 'GMP,Pari';
458
459 The following would first try to find Math::BigInt::Foo, then
460 Math::BigInt::Bar, and when this also fails, revert to
461 Math::BigInt::Calc:
462
463 use Math::BigFloat lib => 'Foo,Math::BigInt::Bar';
464
465 See the respective low-level library documentation for further details.
466
467 Please note that Math::BigFloat does not use the denoted library
468 itself, but it merely passes the lib argument to Math::BigInt. So,
469 instead of the need to do:
470
471 use Math::BigInt lib => 'GMP';
472 use Math::BigFloat;
473
474 you can roll it all into one line:
475
476 use Math::BigFloat lib => 'GMP';
477
478 It is also possible to just require Math::BigFloat:
479
480 require Math::BigFloat;
481
482 This will load the necessary things (like BigInt) when they are needed,
483 and automatically.
484
485 See Math::BigInt for more details than you ever wanted to know about
486 using a different low-level library.
487
488 Using Math::BigInt::Lite
489 For backwards compatibility reasons it is still possible to request a
490 different storage class for use with Math::BigFloat:
491
492 use Math::BigFloat with => 'Math::BigInt::Lite';
493
494 However, this request is ignored, as the current code now uses the low-
495 level math libary for directly storing the number parts.
496
498 "Math::BigFloat" exports nothing by default, but can export the "bpi()"
499 method:
500
501 use Math::BigFloat qw/bpi/;
502
503 print bpi(10), "\n";
504
506 Please see the file BUGS in the CPAN distribution Math::BigInt for
507 known bugs.
508
510 Do not try to be clever to insert some operations in between switching
511 libraries:
512
513 require Math::BigFloat;
514 my $matter = Math::BigFloat->bone() + 4; # load BigInt and Calc
515 Math::BigFloat->import( lib => 'Pari' ); # load Pari, too
516 my $anti_matter = Math::BigFloat->bone()+4; # now use Pari
517
518 This will create objects with numbers stored in two different backend
519 libraries, and VERY BAD THINGS will happen when you use these together:
520
521 my $flash_and_bang = $matter + $anti_matter; # Don't do this!
522
523 stringify, bstr()
524 Both stringify and bstr() now drop the leading '+'. The old code would
525 return '+1.23', the new returns '1.23'. See the documentation in
526 Math::BigInt for reasoning and details.
527
528 bdiv
529 The following will probably not print what you expect:
530
531 print $c->bdiv(123.456),"\n";
532
533 It prints both quotient and reminder since print works in list
534 context. Also, bdiv() will modify $c, so be careful. You probably want
535 to use
536
537 print $c / 123.456,"\n";
538 print scalar $c->bdiv(123.456),"\n"; # or if you want to modify $c
539
540 instead.
541
542 brsft
543 The following will probably not print what you expect:
544
545 my $c = Math::BigFloat->new('3.14159');
546 print $c->brsft(3,10),"\n"; # prints 0.00314153.1415
547
548 It prints both quotient and remainder, since print calls "brsft()" in
549 list context. Also, "$c->brsft()" will modify $c, so be careful. You
550 probably want to use
551
552 print scalar $c->copy()->brsft(3,10),"\n";
553 # or if you really want to modify $c
554 print scalar $c->brsft(3,10),"\n";
555
556 instead.
557
558 Modifying and =
559 Beware of:
560
561 $x = Math::BigFloat->new(5);
562 $y = $x;
563
564 It will not do what you think, e.g. making a copy of $x. Instead it
565 just makes a second reference to the same object and stores it in $y.
566 Thus anything that modifies $x will modify $y (except overloaded math
567 operators), and vice versa. See Math::BigInt for details and how to
568 avoid that.
569
570 bpow
571 "bpow()" now modifies the first argument, unlike the old code which
572 left it alone and only returned the result. This is to be consistent
573 with "badd()" etc. The first will modify $x, the second one won't:
574
575 print bpow($x,$i),"\n"; # modify $x
576 print $x->bpow($i),"\n"; # ditto
577 print $x ** $i,"\n"; # leave $x alone
578
579 precision() vs. accuracy()
580 A common pitfall is to use precision() when you want to round a result
581 to a certain number of digits:
582
583 use Math::BigFloat;
584
585 Math::BigFloat->precision(4); # does not do what you think it does
586 my $x = Math::BigFloat->new(12345); # rounds $x to "12000"!
587 print "$x\n"; # print "12000"
588 my $y = Math::BigFloat->new(3); # rounds $y to "0"!
589 print "$y\n"; # print "0"
590 $z = $x / $y; # 12000 / 0 => NaN!
591 print "$z\n";
592 print $z->precision(),"\n"; # 4
593
594 Replacing precision with accuracy is probably not what you want,
595 either:
596
597 use Math::BigFloat;
598
599 Math::BigFloat->accuracy(4); # enables global rounding:
600 my $x = Math::BigFloat->new(123456); # rounded immediately to "12350"
601 print "$x\n"; # print "123500"
602 my $y = Math::BigFloat->new(3); # rounded to "3
603 print "$y\n"; # print "3"
604 print $z = $x->copy()->bdiv($y),"\n"; # 41170
605 print $z->accuracy(),"\n"; # 4
606
607 What you want to use instead is:
608
609 use Math::BigFloat;
610
611 my $x = Math::BigFloat->new(123456); # no rounding
612 print "$x\n"; # print "123456"
613 my $y = Math::BigFloat->new(3); # no rounding
614 print "$y\n"; # print "3"
615 print $z = $x->copy()->bdiv($y,4),"\n"; # 41150
616 print $z->accuracy(),"\n"; # undef
617
618 In addition to computing what you expected, the last example also does
619 not "taint" the result with an accuracy or precision setting, which
620 would influence any further operation.
621
623 Math::BigInt, Math::BigRat and Math::Big as well as
624 Math::BigInt::BitVect, Math::BigInt::Pari and Math::BigInt::GMP.
625
626 The pragmas bignum, bigint and bigrat might also be of interest because
627 they solve the autoupgrading/downgrading issue, at least partly.
628
629 The package at <http://search.cpan.org/~tels/Math-BigInt> contains more
630 documentation including a full version history, testcases, empty
631 subclass files and benchmarks.
632
634 This program is free software; you may redistribute it and/or modify it
635 under the same terms as Perl itself.
636
638 Mark Biggar, overloaded interface by Ilya Zakharevich. Completely
639 rewritten by Tels <http://bloodgate.com> in 2001 - 2006, and still at
640 it in 2007.
641
642
643
644perl v5.10.1 2009-02-12 Math::BigFloat(3pm)