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        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 pre-
50        # serve $x, use $z = $x->copy()->bXXX($y); See under L</CAVEATS> for
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 exponentiation (($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

DESCRIPTION

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 global 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

METHODS

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()" in Math::BigInt, "bround()" in Math::BigInt or
326       "bfround()" in Math::BigInt or by passing the desired accuracy to the
327       math operation as additional parameter:
328
329               my $x = Math::BigInt->new(30000);
330               my $y = Math::BigInt->new(7);
331               print scalar $x->copy()->bdiv($y, 2);           # print 4300
332               print scalar $x->copy()->bdiv($y)->bround(2);   # print 4300
333
334   precision()
335               $x->precision(-2);      # local for $x, round at the second
336                                       # digit right of the dot
337               $x->precision(2);       # ditto, round at the second digit left
338                                       # of the dot
339
340               CLASS->precision(5);    # Global for all members of CLASS
341                                       # This also applies to new()!
342               CLASS->precision(-5);   # ditto
343
344               $P = CLASS->precision();    # read out global precision
345               $P = $x->precision();       # read out precision that affects $x
346
347       Note: You probably want to use "accuracy" instead. With "accuracy" you
348       set the number of digits each result should have, with "precision()"
349       you set the place where to round!
350
351   bexp()
352               $x->bexp($accuracy);            # calculate e ** X
353
354       Calculates the expression "e ** $x" where "e" is Euler's number.
355
356       This method was added in v1.82 of Math::BigInt (April 2007).
357
358   bnok()
359               $x->bnok($y);   # x over y (binomial coefficient n over k)
360
361       Calculates the binomial coefficient n over k, also called the "choose"
362       function. The result is equivalent to:
363
364               ( n )      n!
365               | - |  = -------
366               ( k )    k!(n-k)!
367
368       This method was added in v1.84 of Math::BigInt (April 2007).
369
370   bpi()
371               print Math::BigFloat->bpi(100), "\n";
372
373       Calculate PI to N digits (including the 3 before the dot). The result
374       is rounded according to the current rounding mode, which defaults to
375       "even".
376
377       This method was added in v1.87 of Math::BigInt (June 2007).
378
379   bcos()
380               my $x = Math::BigFloat->new(1);
381               print $x->bcos(100), "\n";
382
383       Calculate the cosinus of $x, modifying $x in place.
384
385       This method was added in v1.87 of Math::BigInt (June 2007).
386
387   bsin()
388               my $x = Math::BigFloat->new(1);
389               print $x->bsin(100), "\n";
390
391       Calculate the sinus of $x, modifying $x in place.
392
393       This method was added in v1.87 of Math::BigInt (June 2007).
394
395   batan2()
396               my $y = Math::BigFloat->new(2);
397               my $x = Math::BigFloat->new(3);
398               print $y->batan2($x), "\n";
399
400       Calculate the arcus tanges of $y divided by $x, modifying $y in place.
401       See also "batan()".
402
403       This method was added in v1.87 of Math::BigInt (June 2007).
404
405   batan()
406               my $x = Math::BigFloat->new(1);
407               print $x->batan(100), "\n";
408
409       Calculate the arcus tanges of $x, modifying $x in place. See also
410       "batan2()".
411
412       This method was added in v1.87 of Math::BigInt (June 2007).
413
414   bmuladd()
415               $x->bmuladd($y,$z);
416
417       Multiply $x by $y, and then add $z to the result.
418
419       This method was added in v1.87 of Math::BigInt (June 2007).
420

Autocreating constants

422       After "use Math::BigFloat ':constant'" all the floating point constants
423       in the given scope are converted to "Math::BigFloat". This conversion
424       happens at compile time.
425
426       In particular
427
428         perl -MMath::BigFloat=:constant -e 'print 2E-100,"\n"'
429
430       prints the value of "2E-100". Note that without conversion of constants
431       the expression 2E-100 will be calculated as normal floating point
432       number.
433
434       Please note that ':constant' does not affect integer constants, nor
435       binary nor hexadecimal constants. Use bignum or Math::BigInt to get
436       this to work.
437
438   Math library
439       Math with the numbers is done (by default) by a module called
440       Math::BigInt::Calc. This is equivalent to saying:
441
442               use Math::BigFloat lib => 'Calc';
443
444       You can change this by using:
445
446               use Math::BigFloat lib => 'GMP';
447
448       Note: General purpose packages should not be explicit about the library
449       to use; let the script author decide which is best.
450
451       Note: The keyword 'lib' will warn when the requested library could not
452       be loaded. To suppress the warning use 'try' instead:
453
454               use Math::BigFloat try => 'GMP';
455
456       If your script works with huge numbers and Calc is too slow for them,
457       you can also for the loading of one of these libraries and if none of
458       them can be used, the code will die:
459
460               use Math::BigFloat only => 'GMP,Pari';
461
462       The following would first try to find Math::BigInt::Foo, then
463       Math::BigInt::Bar, and when this also fails, revert to
464       Math::BigInt::Calc:
465
466               use Math::BigFloat lib => 'Foo,Math::BigInt::Bar';
467
468       See the respective low-level library documentation for further details.
469
470       Please note that Math::BigFloat does not use the denoted library
471       itself, but it merely passes the lib argument to Math::BigInt. So,
472       instead of the need to do:
473
474               use Math::BigInt lib => 'GMP';
475               use Math::BigFloat;
476
477       you can roll it all into one line:
478
479               use Math::BigFloat lib => 'GMP';
480
481       It is also possible to just require Math::BigFloat:
482
483               require Math::BigFloat;
484
485       This will load the necessary things (like BigInt) when they are needed,
486       and automatically.
487
488       See Math::BigInt for more details than you ever wanted to know about
489       using a different low-level library.
490
491   Using Math::BigInt::Lite
492       For backwards compatibility reasons it is still possible to request a
493       different storage class for use with Math::BigFloat:
494
495               use Math::BigFloat with => 'Math::BigInt::Lite';
496
497       However, this request is ignored, as the current code now uses the low-
498       level math library for directly storing the number parts.
499

EXPORTS

501       "Math::BigFloat" exports nothing by default, but can export the "bpi()"
502       method:
503
504               use Math::BigFloat qw/bpi/;
505
506               print bpi(10), "\n";
507

BUGS

509       Please see the file BUGS in the CPAN distribution Math::BigInt for
510       known bugs.
511

CAVEATS

513       Do not try to be clever to insert some operations in between switching
514       libraries:
515
516           require Math::BigFloat;
517           my $matter = Math::BigFloat->bone() + 4;    # load BigInt and Calc
518           Math::BigFloat->import( lib => 'Pari' );    # load Pari, too
519           my $anti_matter = Math::BigFloat->bone()+4; # now use Pari
520
521       This will create objects with numbers stored in two different backend
522       libraries, and VERY BAD THINGS will happen when you use these together:
523
524               my $flash_and_bang = $matter + $anti_matter;    # Don't do this!
525
526       stringify, bstr()
527        Both stringify and bstr() now drop the leading '+'. The old code would
528        return '+1.23', the new returns '1.23'. See the documentation in
529        Math::BigInt for reasoning and details.
530
531       bdiv
532        The following will probably not print what you expect:
533
534                print $c->bdiv(123.456),"\n";
535
536        It prints both quotient and remainder since print works in list
537        context. Also, bdiv() will modify $c, so be careful. You probably want
538        to use
539
540            print $c / 123.456,"\n";
541            print scalar $c->bdiv(123.456),"\n";  # or if you want to modify $c
542
543        instead.
544
545       brsft
546        The following will probably not print what you expect:
547
548                my $c = Math::BigFloat->new('3.14159');
549                print $c->brsft(3,10),"\n";     # prints 0.00314153.1415
550
551        It prints both quotient and remainder, since print calls "brsft()" in
552        list context. Also, "$c->brsft()" will modify $c, so be careful.  You
553        probably want to use
554
555                print scalar $c->copy()->brsft(3,10),"\n";
556                # or if you really want to modify $c
557                print scalar $c->brsft(3,10),"\n";
558
559        instead.
560
561       Modifying and =
562        Beware of:
563
564                $x = Math::BigFloat->new(5);
565                $y = $x;
566
567        It will not do what you think, e.g. making a copy of $x. Instead it
568        just makes a second reference to the same object and stores it in $y.
569        Thus anything that modifies $x will modify $y (except overloaded math
570        operators), and vice versa. See Math::BigInt for details and how to
571        avoid that.
572
573       bpow
574        "bpow()" now modifies the first argument, unlike the old code which
575        left it alone and only returned the result. This is to be consistent
576        with "badd()" etc. The first will modify $x, the second one won't:
577
578                print bpow($x,$i),"\n";         # modify $x
579                print $x->bpow($i),"\n";        # ditto
580                print $x ** $i,"\n";            # leave $x alone
581
582       precision() vs. accuracy()
583        A common pitfall is to use "precision()" when you want to round a
584        result to a certain number of digits:
585
586            use Math::BigFloat;
587
588            Math::BigFloat->precision(4);            # does not do what you
589                                                     # think it does
590            my $x = Math::BigFloat->new(12345);      # rounds $x to "12000"!
591            print "$x\n";                            # print "12000"
592            my $y = Math::BigFloat->new(3);          # rounds $y to "0"!
593            print "$y\n";                            # print "0"
594            $z = $x / $y;                            # 12000 / 0 => NaN!
595            print "$z\n";
596            print $z->precision(),"\n";              # 4
597
598        Replacing "precision()" with "accuracy" is probably not what you want,
599        either:
600
601            use Math::BigFloat;
602
603            Math::BigFloat->accuracy(4);             # enables global rounding:
604            my $x = Math::BigFloat->new(123456);     # rounded immediately
605                                                     #   to "12350"
606            print "$x\n";                            # print "123500"
607            my $y = Math::BigFloat->new(3);          # rounded to "3
608            print "$y\n";                            # print "3"
609            print $z = $x->copy()->bdiv($y),"\n";    # 41170
610            print $z->accuracy(),"\n";               # 4
611
612        What you want to use instead is:
613
614            use Math::BigFloat;
615
616            my $x = Math::BigFloat->new(123456);     # no rounding
617            print "$x\n";                            # print "123456"
618            my $y = Math::BigFloat->new(3);          # no rounding
619            print "$y\n";                            # print "3"
620            print $z = $x->copy()->bdiv($y,4),"\n";  # 41150
621            print $z->accuracy(),"\n";               # undef
622
623        In addition to computing what you expected, the last example also does
624        not "taint" the result with an accuracy or precision setting, which
625        would influence any further operation.
626

SEE ALSO

628       Math::BigInt, Math::BigRat and Math::Big as well as
629       Math::BigInt::BitVect, Math::BigInt::Pari and  Math::BigInt::GMP.
630
631       The pragmas bignum, bigint and bigrat might also be of interest because
632       they solve the autoupgrading/downgrading issue, at least partly.
633
634       The package at http://search.cpan.org/~tels/Math-BigInt
635       <http://search.cpan.org/~tels/Math-BigInt> contains more documentation
636       including a full version history, testcases, empty subclass files and
637       benchmarks.
638

LICENSE

640       This program is free software; you may redistribute it and/or modify it
641       under the same terms as Perl itself.
642

AUTHORS

644       Mark Biggar, overloaded interface by Ilya Zakharevich.  Completely
645       rewritten by Tels <http://bloodgate.com> in 2001 - 2006, and still at
646       it in 2007.
647
648
649
650perl v5.16.3                      2013-03-04               Math::BigFloat(3pm)
Impressum