1Math::BigFloat(3pm)    Perl Programmers Reference Guide    Math::BigFloat(3pm)
2
3
4

NAME

6       Math::BigFloat - Arbitrary size floating point math package
7

SYNOPSIS

9         use Math::BigFloat;
10
11         # Number creation
12         $x = Math::BigFloat->new($str);       # defaults to 0
13         $nan  = Math::BigFloat->bnan();       # create a NotANumber
14         $zero = Math::BigFloat->bzero();      # create a +0
15         $inf = Math::BigFloat->binf();        # create a +inf
16         $inf = Math::BigFloat->binf('-');     # create a -inf
17         $one = Math::BigFloat->bone();        # create a +1
18         $one = Math::BigFloat->bone('-');     # create a -1
19
20         # Testing
21         $x->is_zero();                # true if arg is +0
22         $x->is_nan();                 # true if arg is NaN
23         $x->is_one();                 # true if arg is +1
24         $x->is_one('-');              # true if arg is -1
25         $x->is_odd();                 # true if odd, false for even
26         $x->is_even();                # true if even, false for odd
27         $x->is_pos();                 # true if >= 0
28         $x->is_neg();                 # true if <  0
29         $x->is_inf(sign);             # true if +inf, or -inf (default is '+')
30
31         $x->bcmp($y);                 # compare numbers (undef,<0,=0,>0)
32         $x->bacmp($y);                # compare absolutely (undef,<0,=0,>0)
33         $x->sign();                   # return the sign, either +,- or NaN
34         $x->digit($n);                # return the nth digit, counting from right
35         $x->digit(-$n);               # return the nth digit, counting from left
36
37         # The following all modify their first argument. If you want to preserve
38         # $x, use $z = $x->copy()->bXXX($y); See under L<CAVEATS> for why this is
39         # neccessary when mixing $a = $b assigments with non-overloaded math.
40
41         # set
42         $x->bzero();                  # set $i to 0
43         $x->bnan();                   # set $i to NaN
44         $x->bone();                   # set $x to +1
45         $x->bone('-');                # set $x to -1
46         $x->binf();                   # set $x to inf
47         $x->binf('-');                # set $x to -inf
48
49         $x->bneg();                   # negation
50         $x->babs();                   # absolute value
51         $x->bnorm();                  # normalize (no-op)
52         $x->bnot();                   # two's complement (bit wise not)
53         $x->binc();                   # increment x by 1
54         $x->bdec();                   # decrement x by 1
55
56         $x->badd($y);                 # addition (add $y to $x)
57         $x->bsub($y);                 # subtraction (subtract $y from $x)
58         $x->bmul($y);                 # multiplication (multiply $x by $y)
59         $x->bdiv($y);                 # divide, set $x to quotient
60                                       # return (quo,rem) or quo if scalar
61
62         $x->bmod($y);                 # modulus ($x % $y)
63         $x->bpow($y);                 # power of arguments ($x ** $y)
64         $x->blsft($y);                # left shift
65         $x->brsft($y);                # right shift
66                                       # return (quo,rem) or quo if scalar
67
68         $x->blog();                   # logarithm of $x to base e (Euler's number)
69         $x->blog($base);              # logarithm of $x to base $base (f.i. 2)
70
71         $x->band($y);                 # bit-wise and
72         $x->bior($y);                 # bit-wise inclusive or
73         $x->bxor($y);                 # bit-wise exclusive or
74         $x->bnot();                   # bit-wise not (two's complement)
75
76         $x->bsqrt();                  # calculate square-root
77         $x->broot($y);                # $y'th root of $x (e.g. $y == 3 => cubic root)
78         $x->bfac();                   # factorial of $x (1*2*3*4*..$x)
79
80         $x->bround($N);               # accuracy: preserve $N digits
81         $x->bfround($N);              # precision: round to the $Nth digit
82
83         $x->bfloor();                 # return integer less or equal than $x
84         $x->bceil();                  # return integer greater or equal than $x
85
86         # The following do not modify their arguments:
87
88         bgcd(@values);                # greatest common divisor
89         blcm(@values);                # lowest common multiplicator
90
91         $x->bstr();                   # return string
92         $x->bsstr();                  # return string in scientific notation
93
94         $x->as_int();                 # return $x as BigInt
95         $x->exponent();               # return exponent as BigInt
96         $x->mantissa();               # return mantissa as BigInt
97         $x->parts();                  # return (mantissa,exponent) as BigInt
98
99         $x->length();                 # number of digits (w/o sign and '.')
100         ($l,$f) = $x->length();       # number of digits, and length of fraction
101
102         $x->precision();              # return P of $x (or global, if P of $x undef)
103         $x->precision($n);            # set P of $x to $n
104         $x->accuracy();               # return A of $x (or global, if A of $x undef)
105         $x->accuracy($n);             # set A $x to $n
106
107         # these get/set the appropriate global value for all BigFloat objects
108         Math::BigFloat->precision();  # Precision
109         Math::BigFloat->accuracy();   # Accuracy
110         Math::BigFloat->round_mode(); # rounding mode
111

DESCRIPTION

113       All operators (inlcuding basic math operations) are overloaded if you
114       declare your big floating point numbers as
115
116         $i = new Math::BigFloat '12_3.456_789_123_456_789E-2';
117
118       Operations with overloaded operators preserve the arguments, which is
119       exactly what you expect.
120
121       Canonical notation
122
123       Input to these routines are either BigFloat objects, or strings of the
124       following four forms:
125
126       · "/^[+-]\d+$/"
127
128       · "/^[+-]\d+\.\d*$/"
129
130       · "/^[+-]\d+E[+-]?\d+$/"
131
132       · "/^[+-]\d*\.\d+E[+-]?\d+$/"
133
134       all with optional leading and trailing zeros and/or spaces. Additon‐
135       ally, numbers are allowed to have an underscore between any two digits.
136
137       Empty strings as well as other illegal numbers results in 'NaN'.
138
139       bnorm() on a BigFloat object is now effectively a no-op, since the num‐
140       bers are always stored in normalized form. On a string, it creates a
141       BigFloat object.
142
143       Output
144
145       Output values are BigFloat objects (normalized), except for bstr() and
146       bsstr().
147
148       The string output will always have leading and trailing zeros stripped
149       and drop a plus sign. "bstr()" will give you always the form with a
150       decimal point, while "bsstr()" (s for scientific) gives you the scien‐
151       tific notation.
152
153               Input                   bstr()          bsstr()
154               '-0'                    '0'             '0E1'
155               '  -123 123 123'        '-123123123'    '-123123123E0'
156               '00.0123'               '0.0123'        '123E-4'
157               '123.45E-2'             '1.2345'        '12345E-4'
158               '10E+3'                 '10000'         '1E4'
159
160       Some routines ("is_odd()", "is_even()", "is_zero()", "is_one()",
161       "is_nan()") return true or false, while others ("bcmp()", "bacmp()")
162       return either undef, <0, 0 or >0 and are suited for sort.
163
164       Actual math is done by using the class defined with "with =" Class;>
165       (which defaults to BigInts) to represent the mantissa and exponent.
166
167       The sign "/^[+-]$/" is stored separately. The string 'NaN' is used to
168       represent the result when input arguments are not numbers, as well as
169       the result of dividing by zero.
170
171       "mantissa()", "exponent()" and "parts()"
172
173       "mantissa()" and "exponent()" return the said parts of the BigFloat as
174       BigInts such that:
175
176               $m = $x->mantissa();
177               $e = $x->exponent();
178               $y = $m * ( 10 ** $e );
179               print "ok\n" if $x == $y;
180
181       "($m,$e) = $x->parts();" is just a shortcut giving you both of them.
182
183       A zero is represented and returned as 0E1, not 0E0 (after Knuth).
184
185       Currently the mantissa is reduced as much as possible, favouring higher
186       exponents over lower ones (e.g. returning 1e7 instead of 10e6 or
187       10000000e0).  This might change in the future, so do not depend on it.
188
189       Accuracy vs. Precision
190
191       See also: Rounding.
192
193       Math::BigFloat supports both precision (rounding to a certain place
194       before or after the dot) and accuracy (rounding to a certain number of
195       digits). For a full documentation, examples and tips on these topics
196       please see the large section about rounding in Math::BigInt.
197
198       Since things like sqrt(2) or "1 / 3" must presented with a limited
199       accuracy lest a operation consumes all resources, each operation pro‐
200       duces no more than the requested number of digits.
201
202       If there is no gloabl precision or accuracy set, and the operation in
203       question was not called with a requested precision or accuracy, and the
204       input $x has no accuracy or precision set, then a fallback parameter
205       will be used. For historical reasons, it is called "div_scale" and can
206       be accessed via:
207
208               $d = Math::BigFloat->div_scale();               # query
209               Math::BigFloat->div_scale($n);                  # set to $n digits
210
211       The default value for "div_scale" is 40.
212
213       In case the result of one operation has more digits than specified, it
214       is rounded. The rounding mode taken is either the default mode, or the
215       one supplied to the operation after the scale:
216
217               $x = Math::BigFloat->new(2);
218               Math::BigFloat->accuracy(5);            # 5 digits max
219               $y = $x->copy()->bdiv(3);               # will give 0.66667
220               $y = $x->copy()->bdiv(3,6);             # will give 0.666667
221               $y = $x->copy()->bdiv(3,6,undef,'odd'); # will give 0.666667
222               Math::BigFloat->round_mode('zero');
223               $y = $x->copy()->bdiv(3,6);             # will also give 0.666667
224
225       Note that "Math::BigFloat->accuracy()" and "Math::BigFloat->preci‐
226       sion()" set the global variables, and thus any newly created number
227       will be subject to the global rounding immidiately. This means that in
228       the examples above, the 3 as argument to "bdiv()" will also get an
229       accuracy of 5.
230
231       It is less confusing to either calculate the result fully, and after‐
232       wards round it explicitely, or use the additional parameters to the
233       math functions like so:
234
235               use Math::BigFloat;
236               $x = Math::BigFloat->new(2);
237               $y = $x->copy()->bdiv(3);
238               print $y->bround(5),"\n";               # will give 0.66667
239
240               or
241
242               use Math::BigFloat;
243               $x = Math::BigFloat->new(2);
244               $y = $x->copy()->bdiv(3,5);             # will give 0.66667
245               print "$y\n";
246
247       Rounding
248
249       ffround ( +$scale )
250         Rounds to the $scale'th place left from the '.', counting from the
251         dot.  The first digit is numbered 1.
252
253       ffround ( -$scale )
254         Rounds to the $scale'th place right from the '.', counting from the
255         dot.
256
257       ffround ( 0 )
258         Rounds to an integer.
259
260       fround  ( +$scale )
261         Preserves accuracy to $scale digits from the left (aka significant
262         digits) and pads the rest with zeros. If the number is between 1 and
263         -1, the significant digits count from the first non-zero after the
264         '.'
265
266       fround  ( -$scale ) and fround ( 0 )
267         These are effectively no-ops.
268
269       All rounding functions take as a second parameter a rounding mode from
270       one of the following: 'even', 'odd', '+inf', '-inf', 'zero' or 'trunc'.
271
272       The default rounding mode is 'even'. By using
273       "Math::BigFloat->round_mode($round_mode);" you can get and set the
274       default mode for subsequent rounding. The usage of
275       "$Math::BigFloat::$round_mode" is no longer supported.  The second
276       parameter to the round functions then overrides the default temporar‐
277       ily.
278
279       The "as_number()" function returns a BigInt from a Math::BigFloat. It
280       uses 'trunc' as rounding mode to make it equivalent to:
281
282               $x = 2.5;
283               $y = int($x) + 2;
284
285       You can override this by passing the desired rounding mode as parameter
286       to "as_number()":
287
288               $x = Math::BigFloat->new(2.5);
289               $y = $x->as_number('odd');      # $y = 3
290

METHODS

292       accuracy
293
294               $x->accuracy(5);                # local for $x
295               CLASS->accuracy(5);             # global for all members of CLASS
296                                               # Note: This also applies to new()!
297
298               $A = $x->accuracy();            # read out accuracy that affects $x
299               $A = CLASS->accuracy();         # read out global accuracy
300
301       Set or get the global or local accuracy, aka how many significant dig‐
302       its the results have. If you set a global accuracy, then this also
303       applies to new()!
304
305       Warning! The accuracy sticks, e.g. once you created a number under the
306       influence of "CLASS->accuracy($A)", all results from math operations
307       with that number will also be rounded.
308
309       In most cases, you should probably round the results explicitely using
310       one of round(), bround() or bfround() or by passing the desired accu‐
311       racy to the math operation as additional parameter:
312
313               my $x = Math::BigInt->new(30000);
314               my $y = Math::BigInt->new(7);
315               print scalar $x->copy()->bdiv($y, 2);           # print 4300
316               print scalar $x->copy()->bdiv($y)->bround(2);   # print 4300
317
318       precision()
319
320               $x->precision(-2);      # local for $x, round at the second digit right of the dot
321               $x->precision(2);       # ditto, round at the second digit left of the dot
322
323               CLASS->precision(5);    # Global for all members of CLASS
324                                       # This also applies to new()!
325               CLASS->precision(-5);   # ditto
326
327               $P = CLASS->precision();        # read out global precision
328               $P = $x->precision();           # read out precision that affects $x
329
330       Note: You probably want to use accuracy() instead. With accuracy you
331       set the number of digits each result should have, with precision you
332       set the place where to round!
333

Autocreating constants

335       After "use Math::BigFloat ':constant'" all the floating point constants
336       in the given scope are converted to "Math::BigFloat". This conversion
337       happens at compile time.
338
339       In particular
340
341         perl -MMath::BigFloat=:constant -e 'print 2E-100,"\n"'
342
343       prints the value of "2E-100". Note that without conversion of constants
344       the expression 2E-100 will be calculated as normal floating point num‐
345       ber.
346
347       Please note that ':constant' does not affect integer constants, nor
348       binary nor hexadecimal constants. Use bignum or Math::BigInt to get
349       this to work.
350
351       Math library
352
353       Math with the numbers is done (by default) by a module called
354       Math::BigInt::Calc. This is equivalent to saying:
355
356               use Math::BigFloat lib => 'Calc';
357
358       You can change this by using:
359
360               use Math::BigFloat lib => 'BitVect';
361
362       The following would first try to find Math::BigInt::Foo, then
363       Math::BigInt::Bar, and when this also fails, revert to Math::Big‐
364       Int::Calc:
365
366               use Math::BigFloat lib => 'Foo,Math::BigInt::Bar';
367
368       Calc.pm uses as internal format an array of elements of some decimal
369       base (usually 1e7, but this might be differen for some systems) with
370       the least significant digit first, while BitVect.pm uses a bit vector
371       of base 2, most significant bit first. Other modules might use even
372       different means of representing the numbers. See the respective module
373       documentation for further details.
374
375       Please note that Math::BigFloat does not use the denoted library
376       itself, but it merely passes the lib argument to Math::BigInt. So,
377       instead of the need to do:
378
379               use Math::BigInt lib => 'GMP';
380               use Math::BigFloat;
381
382       you can roll it all into one line:
383
384               use Math::BigFloat lib => 'GMP';
385
386       It is also possible to just require Math::BigFloat:
387
388               require Math::BigFloat;
389
390       This will load the neccessary things (like BigInt) when they are
391       needed, and automatically.
392
393       Use the lib, Luke! And see "Using Math::BigInt::Lite" for more details
394       than you ever wanted to know about loading a different library.
395
396       Using Math::BigInt::Lite
397
398       It is possible to use Math::BigInt::Lite with Math::BigFloat:
399
400               # 1
401               use Math::BigFloat with => 'Math::BigInt::Lite';
402
403       There is no need to "use Math::BigInt" or "use Math::BigInt::Lite", but
404       you can combine these if you want. For instance, you may want to use
405       Math::BigInt objects in your main script, too.
406
407               # 2
408               use Math::BigInt;
409               use Math::BigFloat with => 'Math::BigInt::Lite';
410
411       Of course, you can combine this with the "lib" parameter.
412
413               # 3
414               use Math::BigFloat with => 'Math::BigInt::Lite', lib => 'GMP,Pari';
415
416       There is no need for a "use Math::BigInt;" statement, even if you want
417       to use Math::BigInt's, since Math::BigFloat will needs Math::BigInt and
418       thus always loads it. But if you add it, add it before:
419
420               # 4
421               use Math::BigInt;
422               use Math::BigFloat with => 'Math::BigInt::Lite', lib => 'GMP,Pari';
423
424       Notice that the module with the last "lib" will "win" and thus it's lib
425       will be used if the lib is available:
426
427               # 5
428               use Math::BigInt lib => 'Bar,Baz';
429               use Math::BigFloat with => 'Math::BigInt::Lite', lib => 'Foo';
430
431       That would try to load Foo, Bar, Baz and Calc (in that order). Or in
432       other words, Math::BigFloat will try to retain previously loaded libs
433       when you don't specify it onem but if you specify one, it will try to
434       load them.
435
436       Actually, the lib loading order would be "Bar,Baz,Calc", and then
437       "Foo,Bar,Baz,Calc", but independend of which lib exists, the result is
438       the same as trying the latter load alone, except for the fact that one
439       of Bar or Baz might be loaded needlessly in an intermidiate step (and
440       thus hang around and waste memory). If neither Bar nor Baz exist (or
441       don't work/compile), they will still be tried to be loaded, but this is
442       not as time/memory consuming as actually loading one of them. Still,
443       this type of usage is not recommended due to these issues.
444
445       The old way (loading the lib only in BigInt) still works though:
446
447               # 6
448               use Math::BigInt lib => 'Bar,Baz';
449               use Math::BigFloat;
450
451       You can even load Math::BigInt afterwards:
452
453               # 7
454               use Math::BigFloat;
455               use Math::BigInt lib => 'Bar,Baz';
456
457       But this has the same problems like #5, it will first load Calc
458       (Math::BigFloat needs Math::BigInt and thus loads it) and then later
459       Bar or Baz, depending on which of them works and is usable/loadable.
460       Since this loads Calc unnecc., it is not recommended.
461
462       Since it also possible to just require Math::BigFloat, this poses the
463       question about what libary this will use:
464
465               require Math::BigFloat;
466               my $x = Math::BigFloat->new(123); $x += 123;
467
468       It will use Calc. Please note that the call to import() is still done,
469       but only when you use for the first time some Math::BigFloat math (it
470       is triggered via any constructor, so the first time you create a
471       Math::BigFloat, the load will happen in the background). This means:
472
473               require Math::BigFloat;
474               Math::BigFloat->import ( lib => 'Foo,Bar' );
475
476       would be the same as:
477
478               use Math::BigFloat lib => 'Foo, Bar';
479
480       But don't try to be clever to insert some operations in between:
481
482               require Math::BigFloat;
483               my $x = Math::BigFloat->bone() + 4;             # load BigInt and Calc
484               Math::BigFloat->import( lib => 'Pari' );        # load Pari, too
485               $x = Math::BigFloat->bone()+4;                  # now use Pari
486
487       While this works, it loads Calc needlessly. But maybe you just wanted
488       that?
489
490       Examples #3 is highly recommended for daily usage.
491

BUGS

493       Please see the file BUGS in the CPAN distribution Math::BigInt for
494       known bugs.
495

CAVEATS

497       stringify, bstr()
498        Both stringify and bstr() now drop the leading '+'. The old code would
499        return '+1.23', the new returns '1.23'. See the documentation in
500        Math::BigInt for reasoning and details.
501
502       bdiv
503        The following will probably not do what you expect:
504
505                print $c->bdiv(123.456),"\n";
506
507        It prints both quotient and reminder since print works in list con‐
508        text. Also, bdiv() will modify $c, so be carefull. You probably want
509        to use
510
511                print $c / 123.456,"\n";
512                print scalar $c->bdiv(123.456),"\n";  # or if you want to modify $c
513
514        instead.
515
516       Modifying and =
517        Beware of:
518
519                $x = Math::BigFloat->new(5);
520                $y = $x;
521
522        It will not do what you think, e.g. making a copy of $x. Instead it
523        just makes a second reference to the same object and stores it in $y.
524        Thus anything that modifies $x will modify $y (except overloaded math
525        operators), and vice versa. See Math::BigInt for details and how to
526        avoid that.
527
528       bpow
529        "bpow()" now modifies the first argument, unlike the old code which
530        left it alone and only returned the result. This is to be consistent
531        with "badd()" etc. The first will modify $x, the second one won't:
532
533                print bpow($x,$i),"\n";         # modify $x
534                print $x->bpow($i),"\n";        # ditto
535                print $x ** $i,"\n";            # leave $x alone
536
537       precision() vs. accuracy()
538        A common pitfall is to use precision() when you want to round a result
539        to a certain number of digits:
540
541                use Math::BigFloat;
542
543                Math::BigFloat->precision(4);           # does not do what you think it does
544                my $x = Math::BigFloat->new(12345);     # rounds $x to "12000"!
545                print "$x\n";                           # print "12000"
546                my $y = Math::BigFloat->new(3);         # rounds $y to "0"!
547                print "$y\n";                           # print "0"
548                $z = $x / $y;                           # 12000 / 0 => NaN!
549                print "$z\n";
550                print $z->precision(),"\n";             # 4
551
552        Replacing precision with accuracy is probably not what you want,
553        either:
554
555                use Math::BigFloat;
556
557                Math::BigFloat->accuracy(4);            # enables global rounding:
558                my $x = Math::BigFloat->new(123456);    # rounded immidiately to "12350"
559                print "$x\n";                           # print "123500"
560                my $y = Math::BigFloat->new(3);         # rounded to "3
561                print "$y\n";                           # print "3"
562                print $z = $x->copy()->bdiv($y),"\n";   # 41170
563                print $z->accuracy(),"\n";              # 4
564
565        What you want to use instead is:
566
567                use Math::BigFloat;
568
569                my $x = Math::BigFloat->new(123456);    # no rounding
570                print "$x\n";                           # print "123456"
571                my $y = Math::BigFloat->new(3);         # no rounding
572                print "$y\n";                           # print "3"
573                print $z = $x->copy()->bdiv($y,4),"\n"; # 41150
574                print $z->accuracy(),"\n";              # undef
575
576        In addition to computing what you expected, the last example also does
577        not "taint" the result with an accuracy or precision setting, which
578        would influence any further operation.
579

SEE ALSO

581       Math::BigInt, Math::BigRat and Math::Big as well as Math::Big‐
582       Int::BitVect, Math::BigInt::Pari and  Math::BigInt::GMP.
583
584       The pragmas bignum, bigint and bigrat might also be of interest because
585       they solve the autoupgrading/downgrading issue, at least partly.
586
587       The package at <http://search.cpan.org/search?mode=mod
588       ule&query=Math%3A%3ABigInt> contains more documentation including a
589       full version history, testcases, empty subclass files and benchmarks.
590

LICENSE

592       This program is free software; you may redistribute it and/or modify it
593       under the same terms as Perl itself.
594

AUTHORS

596       Mark Biggar, overloaded interface by Ilya Zakharevich.  Completely
597       rewritten by Tels <http://bloodgate.com> in 2001 - 2004, and still at
598       it in 2005.
599
600
601
602perl v5.8.8                       2001-09-21               Math::BigFloat(3pm)
Impressum