1Math::BigInt(3)       User Contributed Perl Documentation      Math::BigInt(3)
2
3
4

NAME

6       Math::BigInt - arbitrary size integer math package
7

SYNOPSIS

9         use Math::BigInt;
10
11         # or make it faster with huge numbers: install (optional)
12         # Math::BigInt::GMP and always use (it falls back to
13         # pure Perl if the GMP library is not installed):
14         # (See also the L<MATH LIBRARY> section!)
15
16         # to warn if Math::BigInt::GMP cannot be found, use
17         use Math::BigInt lib => 'GMP';
18
19         # to suppress the warning if Math::BigInt::GMP cannot be found, use
20         # use Math::BigInt try => 'GMP';
21
22         # to die if Math::BigInt::GMP cannot be found, use
23         # use Math::BigInt only => 'GMP';
24
25         # Configuration methods (may be used as class methods and instance methods)
26
27         Math::BigInt->accuracy();     # get class accuracy
28         Math::BigInt->accuracy($n);   # set class accuracy
29         Math::BigInt->precision();    # get class precision
30         Math::BigInt->precision($n);  # set class precision
31         Math::BigInt->round_mode();   # get class rounding mode
32         Math::BigInt->round_mode($m); # set global round mode, must be one of
33                                       # 'even', 'odd', '+inf', '-inf', 'zero',
34                                       # 'trunc', or 'common'
35         Math::BigInt->config();       # return hash with configuration
36
37         # Constructor methods (when the class methods below are used as instance
38         # methods, the value is assigned the invocand)
39
40         $x = Math::BigInt->new($str);             # defaults to 0
41         $x = Math::BigInt->new('0x123');          # from hexadecimal
42         $x = Math::BigInt->new('0b101');          # from binary
43         $x = Math::BigInt->from_hex('cafe');      # from hexadecimal
44         $x = Math::BigInt->from_oct('377');       # from octal
45         $x = Math::BigInt->from_bin('1101');      # from binary
46         $x = Math::BigInt->from_base('why', 36);  # from any base
47         $x = Math::BigInt->from_base_num([1, 0], 2);  # from any base
48         $x = Math::BigInt->bzero();               # create a +0
49         $x = Math::BigInt->bone();                # create a +1
50         $x = Math::BigInt->bone('-');             # create a -1
51         $x = Math::BigInt->binf();                # create a +inf
52         $x = Math::BigInt->binf('-');             # create a -inf
53         $x = Math::BigInt->bnan();                # create a Not-A-Number
54         $x = Math::BigInt->bpi();                 # returns pi
55
56         $y = $x->copy();        # make a copy (unlike $y = $x)
57         $y = $x->as_int();      # return as a Math::BigInt
58         $y = $x->as_float();    # return as a Math::BigFloat
59         $y = $x->as_rat();      # return as a Math::BigRat
60
61         # Boolean methods (these don't modify the invocand)
62
63         $x->is_zero();          # if $x is 0
64         $x->is_one();           # if $x is +1
65         $x->is_one("+");        # ditto
66         $x->is_one("-");        # if $x is -1
67         $x->is_inf();           # if $x is +inf or -inf
68         $x->is_inf("+");        # if $x is +inf
69         $x->is_inf("-");        # if $x is -inf
70         $x->is_nan();           # if $x is NaN
71
72         $x->is_positive();      # if $x > 0
73         $x->is_pos();           # ditto
74         $x->is_negative();      # if $x < 0
75         $x->is_neg();           # ditto
76
77         $x->is_odd();           # if $x is odd
78         $x->is_even();          # if $x is even
79         $x->is_int();           # if $x is an integer
80
81         # Comparison methods
82
83         $x->bcmp($y);           # compare numbers (undef, < 0, == 0, > 0)
84         $x->bacmp($y);          # compare absolutely (undef, < 0, == 0, > 0)
85         $x->beq($y);            # true if and only if $x == $y
86         $x->bne($y);            # true if and only if $x != $y
87         $x->blt($y);            # true if and only if $x < $y
88         $x->ble($y);            # true if and only if $x <= $y
89         $x->bgt($y);            # true if and only if $x > $y
90         $x->bge($y);            # true if and only if $x >= $y
91
92         # Arithmetic methods
93
94         $x->bneg();             # negation
95         $x->babs();             # absolute value
96         $x->bsgn();             # sign function (-1, 0, 1, or NaN)
97         $x->bnorm();            # normalize (no-op)
98         $x->binc();             # increment $x by 1
99         $x->bdec();             # decrement $x by 1
100         $x->badd($y);           # addition (add $y to $x)
101         $x->bsub($y);           # subtraction (subtract $y from $x)
102         $x->bmul($y);           # multiplication (multiply $x by $y)
103         $x->bmuladd($y,$z);     # $x = $x * $y + $z
104         $x->bdiv($y);           # division (floored), set $x to quotient
105                                 # return (quo,rem) or quo if scalar
106         $x->btdiv($y);          # division (truncated), set $x to quotient
107                                 # return (quo,rem) or quo if scalar
108         $x->bmod($y);           # modulus (x % y)
109         $x->btmod($y);          # modulus (truncated)
110         $x->bmodinv($mod);      # modular multiplicative inverse
111         $x->bmodpow($y,$mod);   # modular exponentiation (($x ** $y) % $mod)
112         $x->bpow($y);           # power of arguments (x ** y)
113         $x->blog();             # logarithm of $x to base e (Euler's number)
114         $x->blog($base);        # logarithm of $x to base $base (e.g., base 2)
115         $x->bexp();             # calculate e ** $x where e is Euler's number
116         $x->bnok($y);           # x over y (binomial coefficient n over k)
117         $x->buparrow($n, $y);   # Knuth's up-arrow notation
118         $x->backermann($y);     # the Ackermann function
119         $x->bsin();             # sine
120         $x->bcos();             # cosine
121         $x->batan();            # inverse tangent
122         $x->batan2($y);         # two-argument inverse tangent
123         $x->bsqrt();            # calculate square root
124         $x->broot($y);          # $y'th root of $x (e.g. $y == 3 => cubic root)
125         $x->bfac();             # factorial of $x (1*2*3*4*..$x)
126         $x->bdfac();            # double factorial of $x ($x*($x-2)*($x-4)*...)
127         $x->btfac();            # triple factorial of $x ($x*($x-3)*($x-6)*...)
128         $x->bmfac($k);          # $k'th multi-factorial of $x ($x*($x-$k)*...)
129
130         $x->blsft($n);          # left shift $n places in base 2
131         $x->blsft($n,$b);       # left shift $n places in base $b
132                                 # returns (quo,rem) or quo (scalar context)
133         $x->brsft($n);          # right shift $n places in base 2
134         $x->brsft($n,$b);       # right shift $n places in base $b
135                                 # returns (quo,rem) or quo (scalar context)
136
137         # Bitwise methods
138
139         $x->band($y);           # bitwise and
140         $x->bior($y);           # bitwise inclusive or
141         $x->bxor($y);           # bitwise exclusive or
142         $x->bnot();             # bitwise not (two's complement)
143
144         # Rounding methods
145         $x->round($A,$P,$mode); # round to accuracy or precision using
146                                 # rounding mode $mode
147         $x->bround($n);         # accuracy: preserve $n digits
148         $x->bfround($n);        # $n > 0: round to $nth digit left of dec. point
149                                 # $n < 0: round to $nth digit right of dec. point
150         $x->bfloor();           # round towards minus infinity
151         $x->bceil();            # round towards plus infinity
152         $x->bint();             # round towards zero
153
154         # Other mathematical methods
155
156         $x->bgcd($y);            # greatest common divisor
157         $x->blcm($y);            # least common multiple
158
159         # Object property methods (do not modify the invocand)
160
161         $x->sign();              # the sign, either +, - or NaN
162         $x->digit($n);           # the nth digit, counting from the right
163         $x->digit(-$n);          # the nth digit, counting from the left
164         $x->length();            # return number of digits in number
165         ($xl,$f) = $x->length(); # length of number and length of fraction
166                                  # part, latter is always 0 digits long
167                                  # for Math::BigInt objects
168         $x->mantissa();          # return (signed) mantissa as a Math::BigInt
169         $x->exponent();          # return exponent as a Math::BigInt
170         $x->parts();             # return (mantissa,exponent) as a Math::BigInt
171         $x->sparts();            # mantissa and exponent (as integers)
172         $x->nparts();            # mantissa and exponent (normalised)
173         $x->eparts();            # mantissa and exponent (engineering notation)
174         $x->dparts();            # integer and fraction part
175         $x->fparts();            # numerator and denominator
176         $x->numerator();         # numerator
177         $x->denominator();       # denominator
178
179         # Conversion methods (do not modify the invocand)
180
181         $x->bstr();         # decimal notation, possibly zero padded
182         $x->bsstr();        # string in scientific notation with integers
183         $x->bnstr();        # string in normalized notation
184         $x->bestr();        # string in engineering notation
185         $x->bfstr();        # string in fractional notation
186
187         $x->to_hex();       # as signed hexadecimal string
188         $x->to_bin();       # as signed binary string
189         $x->to_oct();       # as signed octal string
190         $x->to_bytes();     # as byte string
191         $x->to_base($b);    # as string in any base
192         $x->to_base_num($b);   # as array of integers in any base
193
194         $x->as_hex();       # as signed hexadecimal string with prefixed 0x
195         $x->as_bin();       # as signed binary string with prefixed 0b
196         $x->as_oct();       # as signed octal string with prefixed 0
197
198         # Other conversion methods
199
200         $x->numify();           # return as scalar (might overflow or underflow)
201

DESCRIPTION

203       Math::BigInt provides support for arbitrary precision integers.
204       Overloading is also provided for Perl operators.
205
206   Input
207       Input values to these routines may be any scalar number or string that
208       looks like a number and represents an integer. Anything that is
209       accepted by Perl as a literal numeric constant should be accepted by
210       this module, except that finite non-integers return NaN.
211
212       •   Leading and trailing whitespace is ignored.
213
214       •   Leading zeros are ignored, except for floating point numbers with a
215           binary exponent, in which case the number is interpreted as an
216           octal floating point number. For example, "01.4p+0" gives 1.5,
217           "00.4p+0" gives 0.5, but "0.4p+0" gives a NaN. And while "0377"
218           gives 255, "0377p0" gives 255.
219
220       •   If the string has a "0x" or "0X" prefix, it is interpreted as a
221           hexadecimal number.
222
223       •   If the string has a "0o" or "0O" prefix, it is interpreted as an
224           octal number. A floating point literal with a "0" prefix is also
225           interpreted as an octal number.
226
227       •   If the string has a "0b" or "0B" prefix, it is interpreted as a
228           binary number.
229
230       •   Underline characters are allowed in the same way as they are
231           allowed in literal numerical constants.
232
233       •   If the string can not be interpreted, or does not represent a
234           finite integer, NaN is returned.
235
236       •   For hexadecimal, octal, and binary floating point numbers, the
237           exponent must be separated from the significand (mantissa) by the
238           letter "p" or "P", not "e" or "E" as with decimal numbers.
239
240       Some examples of valid string input
241
242           Input string                Resulting value
243
244           123                         123
245           1.23e2                      123
246           12300e-2                    123
247
248           67_538_754                  67538754
249           -4_5_6.7_8_9e+0_1_0         -4567890000000
250
251           0x13a                       314
252           0x13ap0                     314
253           0x1.3ap+8                   314
254           0x0.00013ap+24              314
255           0x13a000p-12                314
256
257           0o472                       314
258           0o1.164p+8                  314
259           0o0.0001164p+20             314
260           0o1164000p-10               314
261
262           0472                        472     Note!
263           01.164p+8                   314
264           00.0001164p+20              314
265           01164000p-10                314
266
267           0b100111010                 314
268           0b1.0011101p+8              314
269           0b0.00010011101p+12         314
270           0b100111010000p-3           314
271
272       Input given as scalar numbers might lose precision. Quote your input to
273       ensure that no digits are lost:
274
275           $x = Math::BigInt->new( 56789012345678901234 );   # bad
276           $x = Math::BigInt->new('56789012345678901234');   # good
277
278       Currently, "Math::BigInt-"new()> (no input argument) and
279       "Math::BigInt-"new("")> return 0. This might change in the future, so
280       always use the following explicit forms to get a zero:
281
282           $zero = Math::BigInt->bzero();
283
284   Output
285       Output values are usually Math::BigInt objects.
286
287       Boolean operators "is_zero()", "is_one()", "is_inf()", etc. return true
288       or false.
289
290       Comparison operators "bcmp()" and "bacmp()") return -1, 0, 1, or undef.
291

METHODS

293   Configuration methods
294       Each of the methods below (except config(), accuracy() and precision())
295       accepts three additional parameters. These arguments $A, $P and $R are
296       "accuracy", "precision" and "round_mode". Please see the section about
297       "ACCURACY and PRECISION" for more information.
298
299       Setting a class variable effects all object instance that are created
300       afterwards.
301
302       accuracy()
303               Math::BigInt->accuracy(5);      # set class accuracy
304               $x->accuracy(5);                # set instance accuracy
305
306               $A = Math::BigInt->accuracy();  # get class accuracy
307               $A = $x->accuracy();            # get instance accuracy
308
309           Set or get the accuracy, i.e., the number of significant digits.
310           The accuracy must be an integer. If the accuracy is set to "undef",
311           no rounding is done.
312
313           Alternatively, one can round the results explicitly using one of
314           "round()", "bround()" or "bfround()" or by passing the desired
315           accuracy to the method as an additional parameter:
316
317               my $x = Math::BigInt->new(30000);
318               my $y = Math::BigInt->new(7);
319               print scalar $x->copy()->bdiv($y, 2);               # prints 4300
320               print scalar $x->copy()->bdiv($y)->bround(2);       # prints 4300
321
322           Please see the section about "ACCURACY and PRECISION" for further
323           details.
324
325               $y = Math::BigInt->new(1234567);    # $y is not rounded
326               Math::BigInt->accuracy(4);          # set class accuracy to 4
327               $x = Math::BigInt->new(1234567);    # $x is rounded automatically
328               print "$x $y";                      # prints "1235000 1234567"
329
330               print $x->accuracy();       # prints "4"
331               print $y->accuracy();       # also prints "4", since
332                                           #   class accuracy is 4
333
334               Math::BigInt->accuracy(5);  # set class accuracy to 5
335               print $x->accuracy();       # prints "4", since instance
336                                           #   accuracy is 4
337               print $y->accuracy();       # prints "5", since no instance
338                                           #   accuracy, and class accuracy is 5
339
340           Note: Each class has it's own globals separated from Math::BigInt,
341           but it is possible to subclass Math::BigInt and make the globals of
342           the subclass aliases to the ones from Math::BigInt.
343
344       precision()
345               Math::BigInt->precision(-2);     # set class precision
346               $x->precision(-2);               # set instance precision
347
348               $P = Math::BigInt->precision();  # get class precision
349               $P = $x->precision();            # get instance precision
350
351           Set or get the precision, i.e., the place to round relative to the
352           decimal point. The precision must be a integer. Setting the
353           precision to $P means that each number is rounded up or down,
354           depending on the rounding mode, to the nearest multiple of 10**$P.
355           If the precision is set to "undef", no rounding is done.
356
357           You might want to use "accuracy()" instead. With "accuracy()" you
358           set the number of digits each result should have, with
359           "precision()" you set the place where to round.
360
361           Please see the section about "ACCURACY and PRECISION" for further
362           details.
363
364               $y = Math::BigInt->new(1234567);    # $y is not rounded
365               Math::BigInt->precision(4);         # set class precision to 4
366               $x = Math::BigInt->new(1234567);    # $x is rounded automatically
367               print $x;                           # prints "1230000"
368
369           Note: Each class has its own globals separated from Math::BigInt,
370           but it is possible to subclass Math::BigInt and make the globals of
371           the subclass aliases to the ones from Math::BigInt.
372
373       div_scale()
374           Set/get the fallback accuracy. This is the accuracy used when
375           neither accuracy nor precision is set explicitly. It is used when a
376           computation might otherwise attempt to return an infinite number of
377           digits.
378
379       round_mode()
380           Set/get the rounding mode.
381
382       upgrade()
383           Set/get the class for upgrading. When a computation might result in
384           a non-integer, the operands are upgraded to this class. This is
385           used for instance by bignum. The default is "undef", i.e., no
386           upgrading.
387
388               # with no upgrading
389               $x = Math::BigInt->new(12);
390               $y = Math::BigInt->new(5);
391               print $x / $y, "\n";                # 2 as a Math::BigInt
392
393               # with upgrading to Math::BigFloat
394               Math::BigInt -> upgrade("Math::BigFloat");
395               print $x / $y, "\n";                # 2.4 as a Math::BigFloat
396
397               # with upgrading to Math::BigRat (after loading Math::BigRat)
398               Math::BigInt -> upgrade("Math::BigRat");
399               print $x / $y, "\n";                # 12/5 as a Math::BigRat
400
401       downgrade()
402           Set/get the class for downgrading. The default is "undef", i.e., no
403           downgrading. Downgrading is not done by Math::BigInt.
404
405       modify()
406               $x->modify('bpowd');
407
408           This method returns 0 if the object can be modified with the given
409           operation, or 1 if not.
410
411           This is used for instance by Math::BigInt::Constant.
412
413       config()
414               Math::BigInt->config("trap_nan" => 1);      # set
415               $accu = Math::BigInt->config("accuracy");   # get
416
417           Set or get class variables. Read-only parameters are marked as RO.
418           Read-write parameters are marked as RW. The following parameters
419           are supported.
420
421               Parameter       RO/RW   Description
422                                       Example
423               ============================================================
424               lib             RO      Name of the math backend library
425                                       Math::BigInt::Calc
426               lib_version     RO      Version of the math backend library
427                                       0.30
428               class           RO      The class of config you just called
429                                       Math::BigRat
430               version         RO      version number of the class you used
431                                       0.10
432               upgrade         RW      To which class numbers are upgraded
433                                       undef
434               downgrade       RW      To which class numbers are downgraded
435                                       undef
436               precision       RW      Global precision
437                                       undef
438               accuracy        RW      Global accuracy
439                                       undef
440               round_mode      RW      Global round mode
441                                       even
442               div_scale       RW      Fallback accuracy for division etc.
443                                       40
444               trap_nan        RW      Trap NaNs
445                                       undef
446               trap_inf        RW      Trap +inf/-inf
447                                       undef
448
449   Constructor methods
450       new()
451               $x = Math::BigInt->new($str,$A,$P,$R);
452
453           Creates a new Math::BigInt object from a scalar or another
454           Math::BigInt object.  The input is accepted as decimal, hexadecimal
455           (with leading '0x'), octal (with leading ('0o') or binary (with
456           leading '0b').
457
458           See "Input" for more info on accepted input formats.
459
460       from_dec()
461               $x = Math::BigInt->from_dec("314159");    # input is decimal
462
463           Interpret input as a decimal. It is equivalent to new(), but does
464           not accept anything but strings representing finite, decimal
465           numbers.
466
467       from_hex()
468               $x = Math::BigInt->from_hex("0xcafe");    # input is hexadecimal
469
470           Interpret input as a hexadecimal string. A "0x" or "x" prefix is
471           optional. A single underscore character may be placed right after
472           the prefix, if present, or between any two digits. If the input is
473           invalid, a NaN is returned.
474
475       from_oct()
476               $x = Math::BigInt->from_oct("0775");      # input is octal
477
478           Interpret the input as an octal string and return the corresponding
479           value. A "0" (zero) prefix is optional. A single underscore
480           character may be placed right after the prefix, if present, or
481           between any two digits. If the input is invalid, a NaN is returned.
482
483       from_bin()
484               $x = Math::BigInt->from_bin("0b10011");   # input is binary
485
486           Interpret the input as a binary string. A "0b" or "b" prefix is
487           optional. A single underscore character may be placed right after
488           the prefix, if present, or between any two digits. If the input is
489           invalid, a NaN is returned.
490
491       from_bytes()
492               $x = Math::BigInt->from_bytes("\xf3\x6b");  # $x = 62315
493
494           Interpret the input as a byte string, assuming big endian byte
495           order. The output is always a non-negative, finite integer.
496
497           In some special cases, from_bytes() matches the conversion done by
498           unpack():
499
500               $b = "\x4e";                             # one char byte string
501               $x = Math::BigInt->from_bytes($b);       # = 78
502               $y = unpack "C", $b;                     # ditto, but scalar
503
504               $b = "\xf3\x6b";                         # two char byte string
505               $x = Math::BigInt->from_bytes($b);       # = 62315
506               $y = unpack "S>", $b;                    # ditto, but scalar
507
508               $b = "\x2d\xe0\x49\xad";                 # four char byte string
509               $x = Math::BigInt->from_bytes($b);       # = 769673645
510               $y = unpack "L>", $b;                    # ditto, but scalar
511
512               $b = "\x2d\xe0\x49\xad\x2d\xe0\x49\xad"; # eight char byte string
513               $x = Math::BigInt->from_bytes($b);       # = 3305723134637787565
514               $y = unpack "Q>", $b;                    # ditto, but scalar
515
516       from_base()
517           Given a string, a base, and an optional collation sequence,
518           interpret the string as a number in the given base. The collation
519           sequence describes the value of each character in the string.
520
521           If a collation sequence is not given, a default collation sequence
522           is used. If the base is less than or equal to 36, the collation
523           sequence is the string consisting of the 36 characters "0" to "9"
524           and "A" to "Z". In this case, the letter case in the input is
525           ignored. If the base is greater than 36, and smaller than or equal
526           to 62, the collation sequence is the string consisting of the 62
527           characters "0" to "9", "A" to "Z", and "a" to "z". A base larger
528           than 62 requires the collation sequence to be specified explicitly.
529
530           These examples show standard binary, octal, and hexadecimal
531           conversion. All cases return 250.
532
533               $x = Math::BigInt->from_base("11111010", 2);
534               $x = Math::BigInt->from_base("372", 8);
535               $x = Math::BigInt->from_base("fa", 16);
536
537           When the base is less than or equal to 36, and no collation
538           sequence is given, the letter case is ignored, so both of these
539           also return 250:
540
541               $x = Math::BigInt->from_base("6Y", 16);
542               $x = Math::BigInt->from_base("6y", 16);
543
544           When the base greater than 36, and no collation sequence is given,
545           the default collation sequence contains both uppercase and
546           lowercase letters, so the letter case in the input is not ignored:
547
548               $x = Math::BigInt->from_base("6S", 37);         # $x is 250
549               $x = Math::BigInt->from_base("6s", 37);         # $x is 276
550               $x = Math::BigInt->from_base("121", 3);         # $x is 16
551               $x = Math::BigInt->from_base("XYZ", 36);        # $x is 44027
552               $x = Math::BigInt->from_base("Why", 42);        # $x is 58314
553
554           The collation sequence can be any set of unique characters. These
555           two cases are equivalent
556
557               $x = Math::BigInt->from_base("100", 2, "01");   # $x is 4
558               $x = Math::BigInt->from_base("|--", 2, "-|");   # $x is 4
559
560       from_base_num()
561           Returns a new Math::BigInt object given an array of values and a
562           base. This method is equivalent to "from_base()", but works on
563           numbers in an array rather than characters in a string. Unlike
564           "from_base()", all input values may be arbitrarily large.
565
566               $x = Math::BigInt->from_base_num([1, 1, 0, 1], 2)     # $x is 13
567               $x = Math::BigInt->from_base_num([3, 125, 39], 128)   # $x is 65191
568
569       bzero()
570               $x = Math::BigInt->bzero();
571               $x->bzero();
572
573           Returns a new Math::BigInt object representing zero. If used as an
574           instance method, assigns the value to the invocand.
575
576       bone()
577               $x = Math::BigInt->bone();          # +1
578               $x = Math::BigInt->bone("+");       # +1
579               $x = Math::BigInt->bone("-");       # -1
580               $x->bone();                         # +1
581               $x->bone("+");                      # +1
582               $x->bone('-');                      # -1
583
584           Creates a new Math::BigInt object representing one. The optional
585           argument is either '-' or '+', indicating whether you want plus one
586           or minus one. If used as an instance method, assigns the value to
587           the invocand.
588
589       binf()
590               $x = Math::BigInt->binf($sign);
591
592           Creates a new Math::BigInt object representing infinity. The
593           optional argument is either '-' or '+', indicating whether you want
594           infinity or minus infinity.  If used as an instance method, assigns
595           the value to the invocand.
596
597               $x->binf();
598               $x->binf('-');
599
600       bnan()
601               $x = Math::BigInt->bnan();
602
603           Creates a new Math::BigInt object representing NaN (Not A Number).
604           If used as an instance method, assigns the value to the invocand.
605
606               $x->bnan();
607
608       bpi()
609               $x = Math::BigInt->bpi(100);        # 3
610               $x->bpi(100);                       # 3
611
612           Creates a new Math::BigInt object representing PI. If used as an
613           instance method, assigns the value to the invocand. With
614           Math::BigInt this always returns 3.
615
616           If upgrading is in effect, returns PI, rounded to N digits with the
617           current rounding mode:
618
619               use Math::BigFloat;
620               use Math::BigInt upgrade => "Math::BigFloat";
621               print Math::BigInt->bpi(3), "\n";           # 3.14
622               print Math::BigInt->bpi(100), "\n";         # 3.1415....
623
624       copy()
625               $x->copy();         # make a true copy of $x (unlike $y = $x)
626
627       as_int()
628       as_number()
629           These methods are called when Math::BigInt encounters an object it
630           doesn't know how to handle. For instance, assume $x is a
631           Math::BigInt, or subclass thereof, and $y is defined, but not a
632           Math::BigInt, or subclass thereof. If you do
633
634               $x -> badd($y);
635
636           $y needs to be converted into an object that $x can deal with. This
637           is done by first checking if $y is something that $x might be
638           upgraded to. If that is the case, no further attempts are made. The
639           next is to see if $y supports the method "as_int()". If it does,
640           "as_int()" is called, but if it doesn't, the next thing is to see
641           if $y supports the method "as_number()". If it does, "as_number()"
642           is called. The method "as_int()" (and "as_number()") is expected to
643           return either an object that has the same class as $x, a subclass
644           thereof, or a string that "ref($x)->new()" can parse to create an
645           object.
646
647           "as_number()" is an alias to "as_int()". "as_number" was introduced
648           in v1.22, while "as_int()" was introduced in v1.68.
649
650           In Math::BigInt, "as_int()" has the same effect as "copy()".
651
652       as_float()
653           Return the argument as a Math::BigFloat object.
654
655       as_rat()
656           Return the argument as a Math::BigRat object.
657
658   Boolean methods
659       None of these methods modify the invocand object.
660
661       is_zero()
662               $x->is_zero();              # true if $x is 0
663
664           Returns true if the invocand is zero and false otherwise.
665
666       is_one( [ SIGN ])
667               $x->is_one();               # true if $x is +1
668               $x->is_one("+");            # ditto
669               $x->is_one("-");            # true if $x is -1
670
671           Returns true if the invocand is one and false otherwise.
672
673       is_finite()
674               $x->is_finite();    # true if $x is not +inf, -inf or NaN
675
676           Returns true if the invocand is a finite number, i.e., it is
677           neither +inf, -inf, nor NaN.
678
679       is_inf( [ SIGN ] )
680               $x->is_inf();               # true if $x is +inf
681               $x->is_inf("+");            # ditto
682               $x->is_inf("-");            # true if $x is -inf
683
684           Returns true if the invocand is infinite and false otherwise.
685
686       is_nan()
687               $x->is_nan();               # true if $x is NaN
688
689       is_positive()
690       is_pos()
691               $x->is_positive();          # true if > 0
692               $x->is_pos();               # ditto
693
694           Returns true if the invocand is positive and false otherwise. A
695           "NaN" is neither positive nor negative.
696
697       is_negative()
698       is_neg()
699               $x->is_negative();          # true if < 0
700               $x->is_neg();               # ditto
701
702           Returns true if the invocand is negative and false otherwise. A
703           "NaN" is neither positive nor negative.
704
705       is_non_positive()
706               $x->is_non_positive();      # true if <= 0
707
708           Returns true if the invocand is negative or zero.
709
710       is_non_negative()
711               $x->is_non_negative();      # true if >= 0
712
713           Returns true if the invocand is positive or zero.
714
715       is_odd()
716               $x->is_odd();               # true if odd, false for even
717
718           Returns true if the invocand is odd and false otherwise. "NaN",
719           "+inf", and "-inf" are neither odd nor even.
720
721       is_even()
722               $x->is_even();              # true if $x is even
723
724           Returns true if the invocand is even and false otherwise. "NaN",
725           "+inf", "-inf" are not integers and are neither odd nor even.
726
727       is_int()
728               $x->is_int();               # true if $x is an integer
729
730           Returns true if the invocand is an integer and false otherwise.
731           "NaN", "+inf", "-inf" are not integers.
732
733   Comparison methods
734       None of these methods modify the invocand object. Note that a "NaN" is
735       neither less than, greater than, or equal to anything else, even a
736       "NaN".
737
738       bcmp()
739               $x->bcmp($y);
740
741           Returns -1, 0, 1 depending on whether $x is less than, equal to, or
742           grater than $y. Returns undef if any operand is a NaN.
743
744       bacmp()
745               $x->bacmp($y);
746
747           Returns -1, 0, 1 depending on whether the absolute value of $x is
748           less than, equal to, or grater than the absolute value of $y.
749           Returns undef if any operand is a NaN.
750
751       beq()
752               $x -> beq($y);
753
754           Returns true if and only if $x is equal to $y, and false otherwise.
755
756       bne()
757               $x -> bne($y);
758
759           Returns true if and only if $x is not equal to $y, and false
760           otherwise.
761
762       blt()
763               $x -> blt($y);
764
765           Returns true if and only if $x is equal to $y, and false otherwise.
766
767       ble()
768               $x -> ble($y);
769
770           Returns true if and only if $x is less than or equal to $y, and
771           false otherwise.
772
773       bgt()
774               $x -> bgt($y);
775
776           Returns true if and only if $x is greater than $y, and false
777           otherwise.
778
779       bge()
780               $x -> bge($y);
781
782           Returns true if and only if $x is greater than or equal to $y, and
783           false otherwise.
784
785   Arithmetic methods
786       These methods modify the invocand object and returns it.
787
788       bneg()
789               $x->bneg();
790
791           Negate the number, e.g. change the sign between '+' and '-', or
792           between '+inf' and '-inf', respectively. Does nothing for NaN or
793           zero.
794
795       babs()
796               $x->babs();
797
798           Set the number to its absolute value, e.g. change the sign from '-'
799           to '+' and from '-inf' to '+inf', respectively. Does nothing for
800           NaN or positive numbers.
801
802       bsgn()
803               $x->bsgn();
804
805           Signum function. Set the number to -1, 0, or 1, depending on
806           whether the number is negative, zero, or positive, respectively.
807           Does not modify NaNs.
808
809       bnorm()
810               $x->bnorm();                        # normalize (no-op)
811
812           Normalize the number. This is a no-op and is provided only for
813           backwards compatibility.
814
815       binc()
816               $x->binc();                 # increment x by 1
817
818       bdec()
819               $x->bdec();                 # decrement x by 1
820
821       badd()
822               $x->badd($y);               # addition (add $y to $x)
823
824       bsub()
825               $x->bsub($y);               # subtraction (subtract $y from $x)
826
827       bmul()
828               $x->bmul($y);               # multiplication (multiply $x by $y)
829
830       bmuladd()
831               $x->bmuladd($y,$z);
832
833           Multiply $x by $y, and then add $z to the result,
834
835           This method was added in v1.87 of Math::BigInt (June 2007).
836
837       bdiv()
838               $x->bdiv($y);               # divide, set $x to quotient
839
840           Divides $x by $y by doing floored division (F-division), where the
841           quotient is the floored (rounded towards negative infinity)
842           quotient of the two operands.  In list context, returns the
843           quotient and the remainder. The remainder is either zero or has the
844           same sign as the second operand. In scalar context, only the
845           quotient is returned.
846
847           The quotient is always the greatest integer less than or equal to
848           the real-valued quotient of the two operands, and the remainder
849           (when it is non-zero) always has the same sign as the second
850           operand; so, for example,
851
852                 1 /  4  => ( 0,  1)
853                 1 / -4  => (-1, -3)
854                -3 /  4  => (-1,  1)
855                -3 / -4  => ( 0, -3)
856               -11 /  2  => (-5,  1)
857                11 / -2  => (-5, -1)
858
859           The behavior of the overloaded operator % agrees with the behavior
860           of Perl's built-in % operator (as documented in the perlop
861           manpage), and the equation
862
863               $x == ($x / $y) * $y + ($x % $y)
864
865           holds true for any finite $x and finite, non-zero $y.
866
867           Perl's "use integer" might change the behaviour of % and / for
868           scalars. This is because under 'use integer' Perl does what the
869           underlying C library thinks is right, and this varies. However,
870           "use integer" does not change the way things are done with
871           Math::BigInt objects.
872
873       btdiv()
874               $x->btdiv($y);              # divide, set $x to quotient
875
876           Divides $x by $y by doing truncated division (T-division), where
877           quotient is the truncated (rouneded towards zero) quotient of the
878           two operands. In list context, returns the quotient and the
879           remainder. The remainder is either zero or has the same sign as the
880           first operand. In scalar context, only the quotient is returned.
881
882       bmod()
883               $x->bmod($y);               # modulus (x % y)
884
885           Returns $x modulo $y, i.e., the remainder after floored division
886           (F-division).  This method is like Perl's % operator. See "bdiv()".
887
888       btmod()
889               $x->btmod($y);              # modulus
890
891           Returns the remainer after truncated division (T-division). See
892           "btdiv()".
893
894       bmodinv()
895               $x->bmodinv($mod);          # modular multiplicative inverse
896
897           Returns the multiplicative inverse of $x modulo $mod. If
898
899               $y = $x -> copy() -> bmodinv($mod)
900
901           then $y is the number closest to zero, and with the same sign as
902           $mod, satisfying
903
904               ($x * $y) % $mod = 1 % $mod
905
906           If $x and $y are non-zero, they must be relative primes, i.e.,
907           "bgcd($y, $mod)==1". '"NaN"' is returned when no modular
908           multiplicative inverse exists.
909
910       bmodpow()
911               $num->bmodpow($exp,$mod);           # modular exponentiation
912                                                   # ($num**$exp % $mod)
913
914           Returns the value of $num taken to the power $exp in the modulus
915           $mod using binary exponentiation.  "bmodpow" is far superior to
916           writing
917
918               $num ** $exp % $mod
919
920           because it is much faster - it reduces internal variables into the
921           modulus whenever possible, so it operates on smaller numbers.
922
923           "bmodpow" also supports negative exponents.
924
925               bmodpow($num, -1, $mod)
926
927           is exactly equivalent to
928
929               bmodinv($num, $mod)
930
931       bpow()
932               $x->bpow($y);               # power of arguments (x ** y)
933
934           "bpow()" (and the rounding functions) now modifies the first
935           argument and returns it, unlike the old code which left it alone
936           and only returned the result. This is to be consistent with
937           "badd()" etc. The first three modifies $x, the last one won't:
938
939               print bpow($x,$i),"\n";         # modify $x
940               print $x->bpow($i),"\n";        # ditto
941               print $x **= $i,"\n";           # the same
942               print $x ** $i,"\n";            # leave $x alone
943
944           The form "$x **= $y" is faster than "$x = $x ** $y;", though.
945
946       blog()
947               $x->blog($base, $accuracy);         # logarithm of x to the base $base
948
949           If $base is not defined, Euler's number (e) is used:
950
951               print $x->blog(undef, 100);         # log(x) to 100 digits
952
953       bexp()
954               $x->bexp($accuracy);                # calculate e ** X
955
956           Calculates the expression "e ** $x" where "e" is Euler's number.
957
958           This method was added in v1.82 of Math::BigInt (April 2007).
959
960           See also "blog()".
961
962       bnok()
963               $x->bnok($y);               # x over y (binomial coefficient n over k)
964
965           Calculates the binomial coefficient n over k, also called the
966           "choose" function, which is
967
968               ( n )       n!
969               |   |  = --------
970               ( k )    k!(n-k)!
971
972           when n and k are non-negative. This method implements the full
973           Kronenburg extension (Kronenburg, M.J. "The Binomial Coefficient
974           for Negative Arguments."  18 May 2011.
975           http://arxiv.org/abs/1105.3689/) illustrated by the following
976           pseudo-code:
977
978               if n >= 0 and k >= 0:
979                   return binomial(n, k)
980               if k >= 0:
981                   return (-1)^k*binomial(-n+k-1, k)
982               if k <= n:
983                   return (-1)^(n-k)*binomial(-k-1, n-k)
984               else
985                   return 0
986
987           The behaviour is identical to the behaviour of the Maple and
988           Mathematica function for negative integers n, k.
989
990       buparrow()
991       uparrow()
992               $a -> buparrow($n, $b);         # modifies $a
993               $x = $a -> uparrow($n, $b);     # does not modify $a
994
995           This method implements Knuth's up-arrow notation, where $n is a
996           non-negative integer representing the number of up-arrows. $n = 0
997           gives multiplication, $n = 1 gives exponentiation, $n = 2 gives
998           tetration, $n = 3 gives hexation etc. The following illustrates the
999           relation between the first values of $n.
1000
1001           See <https://en.wikipedia.org/wiki/Knuth%27s_up-arrow_notation>.
1002
1003       backermann()
1004       ackermann()
1005               $m -> backermann($n);           # modifies $a
1006               $x = $m -> ackermann($n);       # does not modify $a
1007
1008           This method implements the Ackermann function:
1009
1010                        / n + 1              if m = 0
1011              A(m, n) = | A(m-1, 1)          if m > 0 and n = 0
1012                        \ A(m-1, A(m, n-1))  if m > 0 and n > 0
1013
1014           Its value grows rapidly, even for small inputs. For example, A(4,
1015           2) is an integer of 19729 decimal digits.
1016
1017           See https://en.wikipedia.org/wiki/Ackermann_function
1018
1019       bsin()
1020               my $x = Math::BigInt->new(1);
1021               print $x->bsin(100), "\n";
1022
1023           Calculate the sine of $x, modifying $x in place.
1024
1025           In Math::BigInt, unless upgrading is in effect, the result is
1026           truncated to an integer.
1027
1028           This method was added in v1.87 of Math::BigInt (June 2007).
1029
1030       bcos()
1031               my $x = Math::BigInt->new(1);
1032               print $x->bcos(100), "\n";
1033
1034           Calculate the cosine of $x, modifying $x in place.
1035
1036           In Math::BigInt, unless upgrading is in effect, the result is
1037           truncated to an integer.
1038
1039           This method was added in v1.87 of Math::BigInt (June 2007).
1040
1041       batan()
1042               my $x = Math::BigFloat->new(0.5);
1043               print $x->batan(100), "\n";
1044
1045           Calculate the arcus tangens of $x, modifying $x in place.
1046
1047           In Math::BigInt, unless upgrading is in effect, the result is
1048           truncated to an integer.
1049
1050           This method was added in v1.87 of Math::BigInt (June 2007).
1051
1052       batan2()
1053               my $x = Math::BigInt->new(1);
1054               my $y = Math::BigInt->new(1);
1055               print $y->batan2($x), "\n";
1056
1057           Calculate the arcus tangens of $y divided by $x, modifying $y in
1058           place.
1059
1060           In Math::BigInt, unless upgrading is in effect, the result is
1061           truncated to an integer.
1062
1063           This method was added in v1.87 of Math::BigInt (June 2007).
1064
1065       bsqrt()
1066               $x->bsqrt();                # calculate square root
1067
1068           "bsqrt()" returns the square root truncated to an integer.
1069
1070           If you want a better approximation of the square root, then use:
1071
1072               $x = Math::BigFloat->new(12);
1073               Math::BigFloat->precision(0);
1074               Math::BigFloat->round_mode('even');
1075               print $x->copy->bsqrt(),"\n";           # 4
1076
1077               Math::BigFloat->precision(2);
1078               print $x->bsqrt(),"\n";                 # 3.46
1079               print $x->bsqrt(3),"\n";                # 3.464
1080
1081       broot()
1082               $x->broot($N);
1083
1084           Calculates the N'th root of $x.
1085
1086       bfac()
1087               $x->bfac();             # factorial of $x
1088
1089           Returns the factorial of $x, i.e., $x*($x-1)*($x-2)*...*2*1, the
1090           product of all positive integers up to and including $x. $x must be
1091           > -1. The factorial of N is commonly written as N!, or N!1, when
1092           using the multifactorial notation.
1093
1094       bdfac()
1095               $x->bdfac();                # double factorial of $x
1096
1097           Returns the double factorial of $x, i.e., $x*($x-2)*($x-4)*... $x
1098           must be > -2. The double factorial of N is commonly written as N!!,
1099           or N!2, when using the multifactorial notation.
1100
1101       btfac()
1102               $x->btfac();            # triple factorial of $x
1103
1104           Returns the triple factorial of $x, i.e., $x*($x-3)*($x-6)*... $x
1105           must be > -3. The triple factorial of N is commonly written as
1106           N!!!, or N!3, when using the multifactorial notation.
1107
1108       bmfac()
1109               $x->bmfac($k);          # $k'th multifactorial of $x
1110
1111           Returns the multi-factorial of $x, i.e., $x*($x-$k)*($x-2*$k)*...
1112           $x must be > -$k. The multi-factorial of N is commonly written as
1113           N!K.
1114
1115       bfib()
1116               $F = $n->bfib();            # a single Fibonacci number
1117               @F = $n->bfib();            # a list of Fibonacci numbers
1118
1119           In scalar context, returns a single Fibonacci number. In list
1120           context, returns a list of Fibonacci numbers. The invocand is the
1121           last element in the output.
1122
1123           The Fibonacci sequence is defined by
1124
1125               F(0) = 0
1126               F(1) = 1
1127               F(n) = F(n-1) + F(n-2)
1128
1129           In list context, F(0) and F(n) is the first and last number in the
1130           output, respectively. For example, if $n is 12, then "@F =
1131           $n->bfib()" returns the following values, F(0) to F(12):
1132
1133               0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144
1134
1135           The sequence can also be extended to negative index n using the re-
1136           arranged recurrence relation
1137
1138               F(n-2) = F(n) - F(n-1)
1139
1140           giving the bidirectional sequence
1141
1142                  n  -7  -6  -5  -4  -3  -2  -1   0   1   2   3   4   5   6   7
1143               F(n)  13  -8   5  -3   2  -1   1   0   1   1   2   3   5   8  13
1144
1145           If $n is -12, the following values, F(0) to F(12), are returned:
1146
1147               0, 1, -1, 2, -3, 5, -8, 13, -21, 34, -55, 89, -144
1148
1149       blucas()
1150               $F = $n->blucas();          # a single Lucas number
1151               @F = $n->blucas();          # a list of Lucas numbers
1152
1153           In scalar context, returns a single Lucas number. In list context,
1154           returns a list of Lucas numbers. The invocand is the last element
1155           in the output.
1156
1157           The Lucas sequence is defined by
1158
1159               L(0) = 2
1160               L(1) = 1
1161               L(n) = L(n-1) + L(n-2)
1162
1163           In list context, L(0) and L(n) is the first and last number in the
1164           output, respectively. For example, if $n is 12, then "@L =
1165           $n->blucas()" returns the following values, L(0) to L(12):
1166
1167               2, 1, 3, 4, 7, 11, 18, 29, 47, 76, 123, 199, 322
1168
1169           The sequence can also be extended to negative index n using the re-
1170           arranged recurrence relation
1171
1172               L(n-2) = L(n) - L(n-1)
1173
1174           giving the bidirectional sequence
1175
1176                  n  -7  -6  -5  -4  -3  -2  -1   0   1   2   3   4   5   6   7
1177               L(n)  29 -18  11  -7   4  -3   1   2   1   3   4   7  11  18  29
1178
1179           If $n is -12, the following values, L(0) to L(-12), are returned:
1180
1181               2, 1, -3, 4, -7, 11, -18, 29, -47, 76, -123, 199, -322
1182
1183       brsft()
1184               $x->brsft($n);              # right shift $n places in base 2
1185               $x->brsft($n, $b);          # right shift $n places in base $b
1186
1187           The latter is equivalent to
1188
1189               $x -> bdiv($b -> copy() -> bpow($n))
1190
1191       blsft()
1192               $x->blsft($n);              # left shift $n places in base 2
1193               $x->blsft($n, $b);          # left shift $n places in base $b
1194
1195           The latter is equivalent to
1196
1197               $x -> bmul($b -> copy() -> bpow($n))
1198
1199   Bitwise methods
1200       band()
1201               $x->band($y);               # bitwise and
1202
1203       bior()
1204               $x->bior($y);               # bitwise inclusive or
1205
1206       bxor()
1207               $x->bxor($y);               # bitwise exclusive or
1208
1209       bnot()
1210               $x->bnot();                 # bitwise not (two's complement)
1211
1212           Two's complement (bitwise not). This is equivalent to, but faster
1213           than,
1214
1215               $x->binc()->bneg();
1216
1217   Rounding methods
1218       round()
1219               $x->round($A,$P,$round_mode);
1220
1221           Round $x to accuracy $A or precision $P using the round mode
1222           $round_mode.
1223
1224       bround()
1225               $x->bround($N);               # accuracy: preserve $N digits
1226
1227           Rounds $x to an accuracy of $N digits.
1228
1229       bfround()
1230               $x->bfround($N);
1231
1232           Rounds to a multiple of 10**$N. Examples:
1233
1234               Input            N          Result
1235
1236               123456.123456    3          123500
1237               123456.123456    2          123450
1238               123456.123456   -2          123456.12
1239               123456.123456   -3          123456.123
1240
1241       bfloor()
1242               $x->bfloor();
1243
1244           Round $x towards minus infinity, i.e., set $x to the largest
1245           integer less than or equal to $x.
1246
1247       bceil()
1248               $x->bceil();
1249
1250           Round $x towards plus infinity, i.e., set $x to the smallest
1251           integer greater than or equal to $x).
1252
1253       bint()
1254               $x->bint();
1255
1256           Round $x towards zero.
1257
1258   Other mathematical methods
1259       bgcd()
1260               $x -> bgcd($y);             # GCD of $x and $y
1261               $x -> bgcd($y, $z, ...);    # GCD of $x, $y, $z, ...
1262
1263           Returns the greatest common divisor (GCD).
1264
1265       blcm()
1266               $x -> blcm($y);             # LCM of $x and $y
1267               $x -> blcm($y, $z, ...);    # LCM of $x, $y, $z, ...
1268
1269           Returns the least common multiple (LCM).
1270
1271   Object property methods
1272       sign()
1273               $x->sign();
1274
1275           Return the sign, of $x, meaning either "+", "-", "-inf", "+inf" or
1276           NaN.
1277
1278           If you want $x to have a certain sign, use one of the following
1279           methods:
1280
1281               $x->babs();                 # '+'
1282               $x->babs()->bneg();         # '-'
1283               $x->bnan();                 # 'NaN'
1284               $x->binf();                 # '+inf'
1285               $x->binf('-');              # '-inf'
1286
1287       digit()
1288               $x->digit($n);       # return the nth digit, counting from right
1289
1290           If $n is negative, returns the digit counting from left.
1291
1292       digitsum()
1293               $x->digitsum();
1294
1295           Computes the sum of the base 10 digits and returns it.
1296
1297       bdigitsum()
1298               $x->bdigitsum();
1299
1300           Computes the sum of the base 10 digits and assigns the result to
1301           the invocand.
1302
1303       length()
1304               $x->length();
1305               ($xl, $fl) = $x->length();
1306
1307           Returns the number of digits in the decimal representation of the
1308           number. In list context, returns the length of the integer and
1309           fraction part. For Math::BigInt objects, the length of the fraction
1310           part is always 0.
1311
1312           The following probably doesn't do what you expect:
1313
1314               $c = Math::BigInt->new(123);
1315               print $c->length(),"\n";                # prints 30
1316
1317           It prints both the number of digits in the number and in the
1318           fraction part since print calls "length()" in list context. Use
1319           something like:
1320
1321               print scalar $c->length(),"\n";         # prints 3
1322
1323       mantissa()
1324               $x->mantissa();
1325
1326           Return the signed mantissa of $x as a Math::BigInt.
1327
1328       exponent()
1329               $x->exponent();
1330
1331           Return the exponent of $x as a Math::BigInt.
1332
1333       parts()
1334               $x->parts();
1335
1336           Returns the significand (mantissa) and the exponent as integers. In
1337           Math::BigFloat, both are returned as Math::BigInt objects.
1338
1339       sparts()
1340           Returns the significand (mantissa) and the exponent as integers. In
1341           scalar context, only the significand is returned. The significand
1342           is the integer with the smallest absolute value. The output of
1343           "sparts()" corresponds to the output from "bsstr()".
1344
1345           In Math::BigInt, this method is identical to "parts()".
1346
1347       nparts()
1348           Returns the significand (mantissa) and exponent corresponding to
1349           normalized notation. In scalar context, only the significand is
1350           returned. For finite non-zero numbers, the significand's absolute
1351           value is greater than or equal to 1 and less than 10. The output of
1352           "nparts()" corresponds to the output from "bnstr()". In
1353           Math::BigInt, if the significand can not be represented as an
1354           integer, upgrading is performed or NaN is returned.
1355
1356       eparts()
1357           Returns the significand (mantissa) and exponent corresponding to
1358           engineering notation. In scalar context, only the significand is
1359           returned. For finite non-zero numbers, the significand's absolute
1360           value is greater than or equal to 1 and less than 1000, and the
1361           exponent is a multiple of 3. The output of "eparts()" corresponds
1362           to the output from "bestr()". In Math::BigInt, if the significand
1363           can not be represented as an integer, upgrading is performed or NaN
1364           is returned.
1365
1366       dparts()
1367           Returns the integer part and the fraction part. If the fraction
1368           part can not be represented as an integer, upgrading is performed
1369           or NaN is returned. The output of "dparts()" corresponds to the
1370           output from "bdstr()".
1371
1372       fparts()
1373           Returns the smallest possible numerator and denominator so that the
1374           numerator divided by the denominator gives back the original value.
1375           For finite numbers, both values are integers. Mnemonic: fraction.
1376
1377       numerator()
1378           Together with "denominator()", returns the smallest integers so
1379           that the numerator divided by the denominator reproduces the
1380           original value. With Math::BigInt, numerator() simply returns a
1381           copy of the invocand.
1382
1383       denominator()
1384           Together with "numerator()", returns the smallest integers so that
1385           the numerator divided by the denominator reproduces the original
1386           value. With Math::BigInt, denominator() always returns either a 1
1387           or a NaN.
1388
1389   String conversion methods
1390       bstr()
1391           Returns a string representing the number using decimal notation. In
1392           Math::BigFloat, the output is zero padded according to the current
1393           accuracy or precision, if any of those are defined.
1394
1395       bsstr()
1396           Returns a string representing the number using scientific notation
1397           where both the significand (mantissa) and the exponent are
1398           integers. The output corresponds to the output from "sparts()".
1399
1400                 123 is returned as "123e+0"
1401                1230 is returned as "123e+1"
1402               12300 is returned as "123e+2"
1403               12000 is returned as "12e+3"
1404               10000 is returned as "1e+4"
1405
1406       bnstr()
1407           Returns a string representing the number using normalized notation,
1408           the most common variant of scientific notation. For finite non-zero
1409           numbers, the absolute value of the significand is greater than or
1410           equal to 1 and less than 10. The output corresponds to the output
1411           from "nparts()".
1412
1413                 123 is returned as "1.23e+2"
1414                1230 is returned as "1.23e+3"
1415               12300 is returned as "1.23e+4"
1416               12000 is returned as "1.2e+4"
1417               10000 is returned as "1e+4"
1418
1419       bestr()
1420           Returns a string representing the number using engineering
1421           notation. For finite non-zero numbers, the absolute value of the
1422           significand is greater than or equal to 1 and less than 1000, and
1423           the exponent is a multiple of 3. The output corresponds to the
1424           output from "eparts()".
1425
1426                 123 is returned as "123e+0"
1427                1230 is returned as "1.23e+3"
1428               12300 is returned as "12.3e+3"
1429               12000 is returned as "12e+3"
1430               10000 is returned as "10e+3"
1431
1432       bdstr()
1433           Returns a string representing the number using decimal notation.
1434           The output corresponds to the output from "dparts()".
1435
1436                 123 is returned as "123"
1437                1230 is returned as "1230"
1438               12300 is returned as "12300"
1439               12000 is returned as "12000"
1440               10000 is returned as "10000"
1441
1442       bfstr()
1443           Returns a string representing the number using fractional notation.
1444           The output corresponds to the output from "fparts()".
1445
1446                   12.345 is returned as "2469/200"
1447                  123.45 is returned as "2469/20"
1448                 1234.5 is returned as "2469/2"
1449                12345 is returned as "12345"
1450               123450 is returned as "123450"
1451
1452       to_hex()
1453               $x->to_hex();
1454
1455           Returns a hexadecimal string representation of the number. See also
1456           from_hex().
1457
1458       to_bin()
1459               $x->to_bin();
1460
1461           Returns a binary string representation of the number. See also
1462           from_bin().
1463
1464       to_oct()
1465               $x->to_oct();
1466
1467           Returns an octal string representation of the number. See also
1468           from_oct().
1469
1470       to_bytes()
1471               $x = Math::BigInt->new("1667327589");
1472               $s = $x->to_bytes();                    # $s = "cafe"
1473
1474           Returns a byte string representation of the number using big endian
1475           byte order.  The invocand must be a non-negative, finite integer.
1476           See also from_bytes().
1477
1478       to_base()
1479               $x = Math::BigInt->new("250");
1480               $x->to_base(2);     # returns "11111010"
1481               $x->to_base(8);     # returns "372"
1482               $x->to_base(16);    # returns "fa"
1483
1484           Returns a string representation of the number in the given base. If
1485           a collation sequence is given, the collation sequence determines
1486           which characters are used in the output.
1487
1488           Here are some more examples
1489
1490               $x = Math::BigInt->new("16")->to_base(3);       # returns "121"
1491               $x = Math::BigInt->new("44027")->to_base(36);   # returns "XYZ"
1492               $x = Math::BigInt->new("58314")->to_base(42);   # returns "Why"
1493               $x = Math::BigInt->new("4")->to_base(2, "-|");  # returns "|--"
1494
1495           See from_base() for information and examples.
1496
1497       to_base_num()
1498           Converts the given number to the given base. This method is
1499           equivalent to "_to_base()", but returns numbers in an array rather
1500           than characters in a string. In the output, the first element is
1501           the most significant. Unlike "_to_base()", all input values may be
1502           arbitrarily large.
1503
1504               $x = Math::BigInt->new(13);
1505               $x->to_base_num(2);                         # returns [1, 1, 0, 1]
1506
1507               $x = Math::BigInt->new(65191);
1508               $x->to_base_num(128);                       # returns [3, 125, 39]
1509
1510       as_hex()
1511               $x->as_hex();
1512
1513           As, "to_hex()", but with a "0x" prefix.
1514
1515       as_bin()
1516               $x->as_bin();
1517
1518           As, "to_bin()", but with a "0b" prefix.
1519
1520       as_oct()
1521               $x->as_oct();
1522
1523           As, "to_oct()", but with a "0" prefix.
1524
1525       as_bytes()
1526           This is just an alias for "to_bytes()".
1527
1528   Other conversion methods
1529       numify()
1530               print $x->numify();
1531
1532           Returns a Perl scalar from $x. It is used automatically whenever a
1533           scalar is needed, for instance in array index operations.
1534
1535   Utility methods
1536       These utility methods are made public
1537
1538       dec_str_to_dec_flt_str()
1539           Takes a string representing any valid number using decimal notation
1540           and converts it to a string representing the same number using
1541           decimal floating point notation. The output consists of five parts
1542           joined together: the sign of the significand, the absolute value of
1543           the significand as the smallest possible integer, the letter "e",
1544           the sign of the exponent, and the absolute value of the exponent.
1545           If the input is invalid, nothing is returned.
1546
1547               $str2 = $class -> dec_str_to_dec_flt_str($str1);
1548
1549           Some examples
1550
1551               Input           Output
1552               31400.00e-4     +314e-2
1553               -0.00012300e8   -123e+2
1554               0               +0e+0
1555
1556       hex_str_to_dec_flt_str()
1557           Takes a string representing any valid number using hexadecimal
1558           notation and converts it to a string representing the same number
1559           using decimal floating point notation. The output has the same
1560           format as that of "dec_str_to_dec_flt_str()".
1561
1562               $str2 = $class -> hex_str_to_dec_flt_str($str1);
1563
1564           Some examples
1565
1566               Input           Output
1567               0xff            +255e+0
1568
1569           Some examples
1570
1571       oct_str_to_dec_flt_str()
1572           Takes a string representing any valid number using octal notation
1573           and converts it to a string representing the same number using
1574           decimal floating point notation. The output has the same format as
1575           that of "dec_str_to_dec_flt_str()".
1576
1577               $str2 = $class -> oct_str_to_dec_flt_str($str1);
1578
1579       bin_str_to_dec_flt_str()
1580           Takes a string representing any valid number using binary notation
1581           and converts it to a string representing the same number using
1582           decimal floating point notation. The output has the same format as
1583           that of "dec_str_to_dec_flt_str()".
1584
1585               $str2 = $class -> bin_str_to_dec_flt_str($str1);
1586
1587       dec_str_to_dec_str()
1588           Takes a string representing any valid number using decimal notation
1589           and converts it to a string representing the same number using
1590           decimal notation. If the number represents an integer, the output
1591           consists of a sign and the absolute value. If the number represents
1592           a non-integer, the output consists of a sign, the integer part of
1593           the number, the decimal point ".", and the fraction part of the
1594           number without any trailing zeros. If the input is invalid, nothing
1595           is returned.
1596
1597       hex_str_to_dec_str()
1598           Takes a string representing any valid number using hexadecimal
1599           notation and converts it to a string representing the same number
1600           using decimal notation. The output has the same format as that of
1601           "dec_str_to_dec_str()".
1602
1603       oct_str_to_dec_str()
1604           Takes a string representing any valid number using octal notation
1605           and converts it to a string representing the same number using
1606           decimal notation. The output has the same format as that of
1607           "dec_str_to_dec_str()".
1608
1609       bin_str_to_dec_str()
1610           Takes a string representing any valid number using binary notation
1611           and converts it to a string representing the same number using
1612           decimal notation. The output has the same format as that of
1613           "dec_str_to_dec_str()".
1614

ACCURACY and PRECISION

1616       Math::BigInt and Math::BigFloat have full support for accuracy and
1617       precision based rounding, both automatically after every operation, as
1618       well as manually.
1619
1620       This section describes the accuracy/precision handling in Math::BigInt
1621       and Math::BigFloat as it used to be and as it is now, complete with an
1622       explanation of all terms and abbreviations.
1623
1624       Not yet implemented things (but with correct description) are marked
1625       with '!', things that need to be answered are marked with '?'.
1626
1627       In the next paragraph follows a short description of terms used here
1628       (because these may differ from terms used by others people or
1629       documentation).
1630
1631       During the rest of this document, the shortcuts A (for accuracy), P
1632       (for precision), F (fallback) and R (rounding mode) are be used.
1633
1634   Precision P
1635       Precision is a fixed number of digits before (positive) or after
1636       (negative) the decimal point. For example, 123.45 has a precision of
1637       -2. 0 means an integer like 123 (or 120). A precision of 2 means at
1638       least two digits to the left of the decimal point are zero, so 123 with
1639       P = 1 becomes 120. Note that numbers with zeros before the decimal
1640       point may have different precisions, because 1200 can have P = 0, 1 or
1641       2 (depending on what the initial value was). It could also have p < 0,
1642       when the digits after the decimal point are zero.
1643
1644       The string output (of floating point numbers) is padded with zeros:
1645
1646           Initial value    P      A       Result          String
1647           ------------------------------------------------------------
1648           1234.01         -3              1000            1000
1649           1234            -2              1200            1200
1650           1234.5          -1              1230            1230
1651           1234.001         1              1234            1234.0
1652           1234.01          0              1234            1234
1653           1234.01          2              1234.01         1234.01
1654           1234.01          5              1234.01         1234.01000
1655
1656       For Math::BigInt objects, no padding occurs.
1657
1658   Accuracy A
1659       Number of significant digits. Leading zeros are not counted. A number
1660       may have an accuracy greater than the non-zero digits when there are
1661       zeros in it or trailing zeros. For example, 123.456 has A of 6, 10203
1662       has 5, 123.0506 has 7, 123.45000 has 8 and 0.000123 has 3.
1663
1664       The string output (of floating point numbers) is padded with zeros:
1665
1666           Initial value    P      A       Result          String
1667           ------------------------------------------------------------
1668           1234.01                 3       1230            1230
1669           1234.01                 6       1234.01         1234.01
1670           1234.1                  8       1234.1          1234.1000
1671
1672       For Math::BigInt objects, no padding occurs.
1673
1674   Fallback F
1675       When both A and P are undefined, this is used as a fallback accuracy
1676       when dividing numbers.
1677
1678   Rounding mode R
1679       When rounding a number, different 'styles' or 'kinds' of rounding are
1680       possible.  (Note that random rounding, as in Math::Round, is not
1681       implemented.)
1682
1683       Directed rounding
1684
1685       These round modes always round in the same direction.
1686
1687       'trunc'
1688           Round towards zero. Remove all digits following the rounding place,
1689           i.e., replace them with zeros. Thus, 987.65 rounded to tens (P=1)
1690           becomes 980, and rounded to the fourth significant digit becomes
1691           987.6 (A=4). 123.456 rounded to the second place after the decimal
1692           point (P=-2) becomes 123.46. This corresponds to the IEEE 754
1693           rounding mode 'roundTowardZero'.
1694
1695       Rounding to nearest
1696
1697       These rounding modes round to the nearest digit. They differ in how
1698       they determine which way to round in the ambiguous case when there is a
1699       tie.
1700
1701       'even'
1702           Round towards the nearest even digit, e.g., when rounding to
1703           nearest integer, -5.5 becomes -6, 4.5 becomes 4, but 4.501 becomes
1704           5. This corresponds to the IEEE 754 rounding mode
1705           'roundTiesToEven'.
1706
1707       'odd'
1708           Round towards the nearest odd digit, e.g., when rounding to nearest
1709           integer, 4.5 becomes 5, -5.5 becomes -5, but 5.501 becomes 6. This
1710           corresponds to the IEEE 754 rounding mode 'roundTiesToOdd'.
1711
1712       '+inf'
1713           Round towards plus infinity, i.e., always round up. E.g., when
1714           rounding to the nearest integer, 4.5 becomes 5, -5.5 becomes -5,
1715           and 4.501 also becomes 5. This corresponds to the IEEE 754 rounding
1716           mode 'roundTiesToPositive'.
1717
1718       '-inf'
1719           Round towards minus infinity, i.e., always round down. E.g., when
1720           rounding to the nearest integer, 4.5 becomes 4, -5.5 becomes -6,
1721           but 4.501 becomes 5. This corresponds to the IEEE 754 rounding mode
1722           'roundTiesToNegative'.
1723
1724       'zero'
1725           Round towards zero, i.e., round positive numbers down and negative
1726           numbers up.  E.g., when rounding to the nearest integer, 4.5
1727           becomes 4, -5.5 becomes -5, but 4.501 becomes 5. This corresponds
1728           to the IEEE 754 rounding mode 'roundTiesToZero'.
1729
1730       'common'
1731           Round away from zero, i.e., round to the number with the largest
1732           absolute value. E.g., when rounding to the nearest integer, -1.5
1733           becomes -2, 1.5 becomes 2 and 1.49 becomes 1. This corresponds to
1734           the IEEE 754 rounding mode 'roundTiesToAway'.
1735
1736       The handling of A & P in MBI/MBF (the old core code shipped with Perl
1737       versions <= 5.7.2) is like this:
1738
1739       Precision
1740             * bfround($p) is able to round to $p number of digits after the decimal
1741               point
1742             * otherwise P is unused
1743
1744       Accuracy (significant digits)
1745             * bround($a) rounds to $a significant digits
1746             * only bdiv() and bsqrt() take A as (optional) parameter
1747               + other operations simply create the same number (bneg etc), or
1748                 more (bmul) of digits
1749               + rounding/truncating is only done when explicitly calling one
1750                 of bround or bfround, and never for Math::BigInt (not implemented)
1751             * bsqrt() simply hands its accuracy argument over to bdiv.
1752             * the documentation and the comment in the code indicate two
1753               different ways on how bdiv() determines the maximum number
1754               of digits it should calculate, and the actual code does yet
1755               another thing
1756               POD:
1757                 max($Math::BigFloat::div_scale,length(dividend)+length(divisor))
1758               Comment:
1759                 result has at most max(scale, length(dividend), length(divisor)) digits
1760               Actual code:
1761                 scale = max(scale, length(dividend)-1,length(divisor)-1);
1762                 scale += length(divisor) - length(dividend);
1763               So for lx = 3, ly = 9, scale = 10, scale will actually be 16 (10
1764               So for lx = 3, ly = 9, scale = 10, scale will actually be 16
1765               (10+9-3). Actually, the 'difference' added to the scale is cal-
1766               culated from the number of "significant digits" in dividend and
1767               divisor, which is derived by looking at the length of the man-
1768               tissa. Which is wrong, since it includes the + sign (oops) and
1769               actually gets 2 for '+100' and 4 for '+101'. Oops again. Thus
1770               124/3 with div_scale=1 will get you '41.3' based on the strange
1771               assumption that 124 has 3 significant digits, while 120/7 will
1772               get you '17', not '17.1' since 120 is thought to have 2 signif-
1773               icant digits. The rounding after the division then uses the
1774               remainder and $y to determine whether it must round up or down.
1775            ?  I have no idea which is the right way. That's why I used a slightly more
1776            ?  simple scheme and tweaked the few failing testcases to match it.
1777
1778       This is how it works now:
1779
1780       Setting/Accessing
1781             * You can set the A global via Math::BigInt->accuracy() or
1782               Math::BigFloat->accuracy() or whatever class you are using.
1783             * You can also set P globally by using Math::SomeClass->precision()
1784               likewise.
1785             * Globals are classwide, and not inherited by subclasses.
1786             * to undefine A, use Math::SomeClass->accuracy(undef);
1787             * to undefine P, use Math::SomeClass->precision(undef);
1788             * Setting Math::SomeClass->accuracy() clears automatically
1789               Math::SomeClass->precision(), and vice versa.
1790             * To be valid, A must be > 0, P can have any value.
1791             * If P is negative, this means round to the P'th place to the right of the
1792               decimal point; positive values mean to the left of the decimal point.
1793               P of 0 means round to integer.
1794             * to find out the current global A, use Math::SomeClass->accuracy()
1795             * to find out the current global P, use Math::SomeClass->precision()
1796             * use $x->accuracy() respective $x->precision() for the local
1797               setting of $x.
1798             * Please note that $x->accuracy() respective $x->precision()
1799               return eventually defined global A or P, when $x's A or P is not
1800               set.
1801
1802       Creating numbers
1803             * When you create a number, you can give the desired A or P via:
1804               $x = Math::BigInt->new($number,$A,$P);
1805             * Only one of A or P can be defined, otherwise the result is NaN
1806             * If no A or P is give ($x = Math::BigInt->new($number) form), then the
1807               globals (if set) will be used. Thus changing the global defaults later on
1808               will not change the A or P of previously created numbers (i.e., A and P of
1809               $x will be what was in effect when $x was created)
1810             * If given undef for A and P, NO rounding will occur, and the globals will
1811               NOT be used. This is used by subclasses to create numbers without
1812               suffering rounding in the parent. Thus a subclass is able to have its own
1813               globals enforced upon creation of a number by using
1814               $x = Math::BigInt->new($number,undef,undef):
1815
1816                   use Math::BigInt::SomeSubclass;
1817                   use Math::BigInt;
1818
1819                   Math::BigInt->accuracy(2);
1820                   Math::BigInt::SomeSubclass->accuracy(3);
1821                   $x = Math::BigInt::SomeSubclass->new(1234);
1822
1823               $x is now 1230, and not 1200. A subclass might choose to implement
1824               this otherwise, e.g. falling back to the parent's A and P.
1825
1826       Usage
1827             * If A or P are enabled/defined, they are used to round the result of each
1828               operation according to the rules below
1829             * Negative P is ignored in Math::BigInt, since Math::BigInt objects never
1830               have digits after the decimal point
1831             * Math::BigFloat uses Math::BigInt internally, but setting A or P inside
1832               Math::BigInt as globals does not tamper with the parts of a Math::BigFloat.
1833               A flag is used to mark all Math::BigFloat numbers as 'never round'.
1834
1835       Precedence
1836             * It only makes sense that a number has only one of A or P at a time.
1837               If you set either A or P on one object, or globally, the other one will
1838               be automatically cleared.
1839             * If two objects are involved in an operation, and one of them has A in
1840               effect, and the other P, this results in an error (NaN).
1841             * A takes precedence over P (Hint: A comes before P).
1842               If neither of them is defined, nothing is used, i.e. the result will have
1843               as many digits as it can (with an exception for bdiv/bsqrt) and will not
1844               be rounded.
1845             * There is another setting for bdiv() (and thus for bsqrt()). If neither of
1846               A or P is defined, bdiv() will use a fallback (F) of $div_scale digits.
1847               If either the dividend's or the divisor's mantissa has more digits than
1848               the value of F, the higher value will be used instead of F.
1849               This is to limit the digits (A) of the result (just consider what would
1850               happen with unlimited A and P in the case of 1/3 :-)
1851             * bdiv will calculate (at least) 4 more digits than required (determined by
1852               A, P or F), and, if F is not used, round the result
1853               (this will still fail in the case of a result like 0.12345000000001 with A
1854               or P of 5, but this can not be helped - or can it?)
1855             * Thus you can have the math done by on Math::Big* class in two modi:
1856               + never round (this is the default):
1857                 This is done by setting A and P to undef. No math operation
1858                 will round the result, with bdiv() and bsqrt() as exceptions to guard
1859                 against overflows. You must explicitly call bround(), bfround() or
1860                 round() (the latter with parameters).
1861                 Note: Once you have rounded a number, the settings will 'stick' on it
1862                 and 'infect' all other numbers engaged in math operations with it, since
1863                 local settings have the highest precedence. So, to get SaferRound[tm],
1864                 use a copy() before rounding like this:
1865
1866                   $x = Math::BigFloat->new(12.34);
1867                   $y = Math::BigFloat->new(98.76);
1868                   $z = $x * $y;                           # 1218.6984
1869                   print $x->copy()->bround(3);            # 12.3 (but A is now 3!)
1870                   $z = $x * $y;                           # still 1218.6984, without
1871                                                           # copy would have been 1210!
1872
1873               + round after each op:
1874                 After each single operation (except for testing like is_zero()), the
1875                 method round() is called and the result is rounded appropriately. By
1876                 setting proper values for A and P, you can have all-the-same-A or
1877                 all-the-same-P modes. For example, Math::Currency might set A to undef,
1878                 and P to -2, globally.
1879
1880            ?Maybe an extra option that forbids local A & P settings would be in order,
1881            ?so that intermediate rounding does not 'poison' further math?
1882
1883       Overriding globals
1884             * you will be able to give A, P and R as an argument to all the calculation
1885               routines; the second parameter is A, the third one is P, and the fourth is
1886               R (shift right by one for binary operations like badd). P is used only if
1887               the first parameter (A) is undefined. These three parameters override the
1888               globals in the order detailed as follows, i.e. the first defined value
1889               wins:
1890               (local: per object, global: global default, parameter: argument to sub)
1891                 + parameter A
1892                 + parameter P
1893                 + local A (if defined on both of the operands: smaller one is taken)
1894                 + local P (if defined on both of the operands: bigger one is taken)
1895                 + global A
1896                 + global P
1897                 + global F
1898             * bsqrt() will hand its arguments to bdiv(), as it used to, only now for two
1899               arguments (A and P) instead of one
1900
1901       Local settings
1902             * You can set A or P locally by using $x->accuracy() or
1903               $x->precision()
1904               and thus force different A and P for different objects/numbers.
1905             * Setting A or P this way immediately rounds $x to the new value.
1906             * $x->accuracy() clears $x->precision(), and vice versa.
1907
1908       Rounding
1909             * the rounding routines will use the respective global or local settings.
1910               bround() is for accuracy rounding, while bfround() is for precision
1911             * the two rounding functions take as the second parameter one of the
1912               following rounding modes (R):
1913               'even', 'odd', '+inf', '-inf', 'zero', 'trunc', 'common'
1914             * you can set/get the global R by using Math::SomeClass->round_mode()
1915               or by setting $Math::SomeClass::round_mode
1916             * after each operation, $result->round() is called, and the result may
1917               eventually be rounded (that is, if A or P were set either locally,
1918               globally or as parameter to the operation)
1919             * to manually round a number, call $x->round($A,$P,$round_mode);
1920               this will round the number by using the appropriate rounding function
1921               and then normalize it.
1922             * rounding modifies the local settings of the number:
1923
1924                   $x = Math::BigFloat->new(123.456);
1925                   $x->accuracy(5);
1926                   $x->bround(4);
1927
1928               Here 4 takes precedence over 5, so 123.5 is the result and $x->accuracy()
1929               will be 4 from now on.
1930
1931       Default values
1932             * R: 'even'
1933             * F: 40
1934             * A: undef
1935             * P: undef
1936
1937       Remarks
1938             * The defaults are set up so that the new code gives the same results as
1939               the old code (except in a few cases on bdiv):
1940               + Both A and P are undefined and thus will not be used for rounding
1941                 after each operation.
1942               + round() is thus a no-op, unless given extra parameters A and P
1943

Infinity and Not a Number

1945       While Math::BigInt has extensive handling of inf and NaN, certain
1946       quirks remain.
1947
1948       oct()/hex()
1949           These perl routines currently (as of Perl v.5.8.6) cannot handle
1950           passed inf.
1951
1952               te@linux:~> perl -wle 'print 2 ** 3333'
1953               Inf
1954               te@linux:~> perl -wle 'print 2 ** 3333 == 2 ** 3333'
1955               1
1956               te@linux:~> perl -wle 'print oct(2 ** 3333)'
1957               0
1958               te@linux:~> perl -wle 'print hex(2 ** 3333)'
1959               Illegal hexadecimal digit 'I' ignored at -e line 1.
1960               0
1961
1962           The same problems occur if you pass them Math::BigInt->binf()
1963           objects. Since overloading these routines is not possible, this
1964           cannot be fixed from Math::BigInt.
1965

INTERNALS

1967       You should neither care about nor depend on the internal
1968       representation; it might change without notice. Use ONLY method calls
1969       like "$x->sign();" instead relying on the internal representation.
1970
1971   MATH LIBRARY
1972       The mathematical computations are performed by a backend library. It is
1973       not required to specify which backend library to use, but some backend
1974       libraries are much faster than the default library.
1975
1976       The default library
1977
1978       The default library is Math::BigInt::Calc, which is implemented in pure
1979       Perl and hence does not require a compiler.
1980
1981       Specifying a library
1982
1983       The simple case
1984
1985           use Math::BigInt;
1986
1987       is equivalent to saying
1988
1989           use Math::BigInt try => 'Calc';
1990
1991       You can use a different backend library with, e.g.,
1992
1993           use Math::BigInt try => 'GMP';
1994
1995       which attempts to load the Math::BigInt::GMP library, and falls back to
1996       the default library if the specified library can't be loaded.
1997
1998       Multiple libraries can be specified by separating them by a comma,
1999       e.g.,
2000
2001           use Math::BigInt try => 'GMP,Pari';
2002
2003       If you request a specific set of libraries and do not allow fallback to
2004       the default library, specify them using "only",
2005
2006           use Math::BigInt only => 'GMP,Pari';
2007
2008       If you prefer a specific set of libraries, but want to see a warning if
2009       the fallback library is used, specify them using "lib",
2010
2011           use Math::BigInt lib => 'GMP,Pari';
2012
2013       The following first tries to find Math::BigInt::Foo, then
2014       Math::BigInt::Bar, and if this also fails, reverts to
2015       Math::BigInt::Calc:
2016
2017           use Math::BigInt try => 'Foo,Math::BigInt::Bar';
2018
2019       Which library to use?
2020
2021       Note: General purpose packages should not be explicit about the library
2022       to use; let the script author decide which is best.
2023
2024       Math::BigInt::GMP, Math::BigInt::Pari, and Math::BigInt::GMPz are in
2025       cases involving big numbers much faster than Math::BigInt::Calc.
2026       However these libraries are slower when dealing with very small numbers
2027       (less than about 20 digits) and when converting very large numbers to
2028       decimal (for instance for printing, rounding, calculating their length
2029       in decimal etc.).
2030
2031       So please select carefully what library you want to use.
2032
2033       Different low-level libraries use different formats to store the
2034       numbers, so mixing them won't work. You should not depend on the number
2035       having a specific internal format.
2036
2037       See the respective math library module documentation for further
2038       details.
2039
2040       Loading multiple libraries
2041
2042       The first library that is successfully loaded is the one that will be
2043       used. Any further attempts at loading a different module will be
2044       ignored. This is to avoid the situation where module A requires math
2045       library X, and module B requires math library Y, causing modules A and
2046       B to be incompatible. For example,
2047
2048           use Math::BigInt;                   # loads default "Calc"
2049           use Math::BigFloat only => "GMP";   # ignores "GMP"
2050
2051   SIGN
2052       The sign is either '+', '-', 'NaN', '+inf' or '-inf'.
2053
2054       A sign of 'NaN' is used to represent the result when input arguments
2055       are not numbers or as a result of 0/0. '+inf' and '-inf' represent plus
2056       respectively minus infinity. You get '+inf' when dividing a positive
2057       number by 0, and '-inf' when dividing any negative number by 0.
2058

EXAMPLES

2060         use Math::BigInt;
2061
2062         sub bigint { Math::BigInt->new(shift); }
2063
2064         $x = Math::BigInt->bstr("1234")       # string "1234"
2065         $x = "$x";                            # same as bstr()
2066         $x = Math::BigInt->bneg("1234");      # Math::BigInt "-1234"
2067         $x = Math::BigInt->babs("-12345");    # Math::BigInt "12345"
2068         $x = Math::BigInt->bnorm("-0.00");    # Math::BigInt "0"
2069         $x = bigint(1) + bigint(2);           # Math::BigInt "3"
2070         $x = bigint(1) + "2";                 # ditto ("2" becomes a Math::BigInt)
2071         $x = bigint(1);                       # Math::BigInt "1"
2072         $x = $x + 5 / 2;                      # Math::BigInt "3"
2073         $x = $x ** 3;                         # Math::BigInt "27"
2074         $x *= 2;                              # Math::BigInt "54"
2075         $x = Math::BigInt->new(0);            # Math::BigInt "0"
2076         $x--;                                 # Math::BigInt "-1"
2077         $x = Math::BigInt->badd(4,5)          # Math::BigInt "9"
2078         print $x->bsstr();                    # 9e+0
2079
2080       Examples for rounding:
2081
2082         use Math::BigFloat;
2083         use Test::More;
2084
2085         $x = Math::BigFloat->new(123.4567);
2086         $y = Math::BigFloat->new(123.456789);
2087         Math::BigFloat->accuracy(4);          # no more A than 4
2088
2089         is ($x->copy()->bround(),123.4);      # even rounding
2090         print $x->copy()->bround(),"\n";      # 123.4
2091         Math::BigFloat->round_mode('odd');    # round to odd
2092         print $x->copy()->bround(),"\n";      # 123.5
2093         Math::BigFloat->accuracy(5);          # no more A than 5
2094         Math::BigFloat->round_mode('odd');    # round to odd
2095         print $x->copy()->bround(),"\n";      # 123.46
2096         $y = $x->copy()->bround(4),"\n";      # A = 4: 123.4
2097         print "$y, ",$y->accuracy(),"\n";     # 123.4, 4
2098
2099         Math::BigFloat->accuracy(undef);      # A not important now
2100         Math::BigFloat->precision(2);         # P important
2101         print $x->copy()->bnorm(),"\n";       # 123.46
2102         print $x->copy()->bround(),"\n";      # 123.46
2103
2104       Examples for converting:
2105
2106         my $x = Math::BigInt->new('0b1'.'01' x 123);
2107         print "bin: ",$x->as_bin()," hex:",$x->as_hex()," dec: ",$x,"\n";
2108

NUMERIC LITERALS

2110       After "use Math::BigInt ':constant'" all numeric literals in the given
2111       scope are converted to "Math::BigInt" objects. This conversion happens
2112       at compile time. Every non-integer is convert to a NaN.
2113
2114       For example,
2115
2116           perl -MMath::BigInt=:constant -le 'print 2**150'
2117
2118       prints the exact value of "2**150". Note that without conversion of
2119       constants to objects the expression "2**150" is calculated using Perl
2120       scalars, which leads to an inaccurate result.
2121
2122       Please note that strings are not affected, so that
2123
2124           use Math::BigInt qw/:constant/;
2125
2126           $x = "1234567890123456789012345678901234567890"
2127                   + "123456789123456789";
2128
2129       does give you what you expect. You need an explicit Math::BigInt->new()
2130       around at least one of the operands. You should also quote large
2131       constants to prevent loss of precision:
2132
2133           use Math::BigInt;
2134
2135           $x = Math::BigInt->new("1234567889123456789123456789123456789");
2136
2137       Without the quotes Perl first converts the large number to a floating
2138       point constant at compile time, and then converts the result to a
2139       Math::BigInt object at run time, which results in an inaccurate result.
2140
2141   Hexadecimal, octal, and binary floating point literals
2142       Perl (and this module) accepts hexadecimal, octal, and binary floating
2143       point literals, but use them with care with Perl versions before
2144       v5.32.0, because some versions of Perl silently give the wrong result.
2145       Below are some examples of different ways to write the number decimal
2146       314.
2147
2148       Hexadecimal floating point literals:
2149
2150           0x1.3ap+8         0X1.3AP+8
2151           0x1.3ap8          0X1.3AP8
2152           0x13a0p-4         0X13A0P-4
2153
2154       Octal floating point literals (with "0" prefix):
2155
2156           01.164p+8         01.164P+8
2157           01.164p8          01.164P8
2158           011640p-4         011640P-4
2159
2160       Octal floating point literals (with "0o" prefix) (requires v5.34.0):
2161
2162           0o1.164p+8        0O1.164P+8
2163           0o1.164p8         0O1.164P8
2164           0o11640p-4        0O11640P-4
2165
2166       Binary floating point literals:
2167
2168           0b1.0011101p+8    0B1.0011101P+8
2169           0b1.0011101p8     0B1.0011101P8
2170           0b10011101000p-2  0B10011101000P-2
2171

PERFORMANCE

2173       Using the form $x += $y; etc over $x = $x + $y is faster, since a copy
2174       of $x must be made in the second case. For long numbers, the copy can
2175       eat up to 20% of the work (in the case of addition/subtraction, less
2176       for multiplication/division). If $y is very small compared to $x, the
2177       form $x += $y is MUCH faster than $x = $x + $y since making the copy of
2178       $x takes more time then the actual addition.
2179
2180       With a technique called copy-on-write, the cost of copying with
2181       overload could be minimized or even completely avoided. A test
2182       implementation of COW did show performance gains for overloaded math,
2183       but introduced a performance loss due to a constant overhead for all
2184       other operations. So Math::BigInt does currently not COW.
2185
2186       The rewritten version of this module (vs. v0.01) is slower on certain
2187       operations, like "new()", "bstr()" and "numify()". The reason are that
2188       it does now more work and handles much more cases. The time spent in
2189       these operations is usually gained in the other math operations so that
2190       code on the average should get (much) faster. If they don't, please
2191       contact the author.
2192
2193       Some operations may be slower for small numbers, but are significantly
2194       faster for big numbers. Other operations are now constant (O(1), like
2195       "bneg()", "babs()" etc), instead of O(N) and thus nearly always take
2196       much less time.  These optimizations were done on purpose.
2197
2198       If you find the Calc module to slow, try to install any of the
2199       replacement modules and see if they help you.
2200
2201   Alternative math libraries
2202       You can use an alternative library to drive Math::BigInt. See the
2203       section "MATH LIBRARY" for more information.
2204
2205       For more benchmark results see
2206       <http://bloodgate.com/perl/benchmarks.html>.
2207

SUBCLASSING

2209   Subclassing Math::BigInt
2210       The basic design of Math::BigInt allows simple subclasses with very
2211       little work, as long as a few simple rules are followed:
2212
2213       •   The public API must remain consistent, i.e. if a sub-class is
2214           overloading addition, the sub-class must use the same name, in this
2215           case badd(). The reason for this is that Math::BigInt is optimized
2216           to call the object methods directly.
2217
2218       •   The private object hash keys like "$x->{sign}" may not be changed,
2219           but additional keys can be added, like "$x->{_custom}".
2220
2221       •   Accessor functions are available for all existing object hash keys
2222           and should be used instead of directly accessing the internal hash
2223           keys. The reason for this is that Math::BigInt itself has a
2224           pluggable interface which permits it to support different storage
2225           methods.
2226
2227       More complex sub-classes may have to replicate more of the logic
2228       internal of Math::BigInt if they need to change more basic behaviors. A
2229       subclass that needs to merely change the output only needs to overload
2230       "bstr()".
2231
2232       All other object methods and overloaded functions can be directly
2233       inherited from the parent class.
2234
2235       At the very minimum, any subclass needs to provide its own "new()" and
2236       can store additional hash keys in the object. There are also some
2237       package globals that must be defined, e.g.:
2238
2239           # Globals
2240           $accuracy = undef;
2241           $precision = -2;       # round to 2 decimal places
2242           $round_mode = 'even';
2243           $div_scale = 40;
2244
2245       Additionally, you might want to provide the following two globals to
2246       allow auto-upgrading and auto-downgrading to work correctly:
2247
2248           $upgrade = undef;
2249           $downgrade = undef;
2250
2251       This allows Math::BigInt to correctly retrieve package globals from the
2252       subclass, like $SubClass::precision. See t/Math/BigInt/Subclass.pm or
2253       t/Math/BigFloat/SubClass.pm completely functional subclass examples.
2254
2255       Don't forget to
2256
2257           use overload;
2258
2259       in your subclass to automatically inherit the overloading from the
2260       parent. If you like, you can change part of the overloading, look at
2261       Math::String for an example.
2262

UPGRADING

2264       When used like this:
2265
2266           use Math::BigInt upgrade => 'Foo::Bar';
2267
2268       certain operations 'upgrade' their calculation and thus the result to
2269       the class Foo::Bar. Usually this is used in conjunction with
2270       Math::BigFloat:
2271
2272           use Math::BigInt upgrade => 'Math::BigFloat';
2273
2274       As a shortcut, you can use the module bignum:
2275
2276           use bignum;
2277
2278       Also good for one-liners:
2279
2280           perl -Mbignum -le 'print 2 ** 255'
2281
2282       This makes it possible to mix arguments of different classes (as in 2.5
2283       + 2) as well es preserve accuracy (as in sqrt(3)).
2284
2285       Beware: This feature is not fully implemented yet.
2286
2287   Auto-upgrade
2288       The following methods upgrade themselves unconditionally; that is if
2289       upgrade is in effect, they always hands up their work:
2290
2291           div bsqrt blog bexp bpi bsin bcos batan batan2
2292
2293       All other methods upgrade themselves only when one (or all) of their
2294       arguments are of the class mentioned in $upgrade.
2295

EXPORTS

2297       "Math::BigInt" exports nothing by default, but can export the following
2298       methods:
2299
2300           bgcd
2301           blcm
2302

CAVEATS

2304       Some things might not work as you expect them. Below is documented what
2305       is known to be troublesome:
2306
2307       Comparing numbers as strings
2308           Both "bstr()" and "bsstr()" as well as stringify via overload drop
2309           the leading '+'. This is to be consistent with Perl and to make
2310           "cmp" (especially with overloading) to work as you expect. It also
2311           solves problems with "Test.pm" and Test::More, which stringify
2312           arguments before comparing them.
2313
2314           Mark Biggar said, when asked about to drop the '+' altogether, or
2315           make only "cmp" work:
2316
2317               I agree (with the first alternative), don't add the '+' on positive
2318               numbers.  It's not as important anymore with the new internal form
2319               for numbers.  It made doing things like abs and neg easier, but
2320               those have to be done differently now anyway.
2321
2322           So, the following examples now works as expected:
2323
2324               use Test::More tests => 1;
2325               use Math::BigInt;
2326
2327               my $x = Math::BigInt -> new(3*3);
2328               my $y = Math::BigInt -> new(3*3);
2329
2330               is($x,3*3, 'multiplication');
2331               print "$x eq 9" if $x eq $y;
2332               print "$x eq 9" if $x eq '9';
2333               print "$x eq 9" if $x eq 3*3;
2334
2335           Additionally, the following still works:
2336
2337               print "$x == 9" if $x == $y;
2338               print "$x == 9" if $x == 9;
2339               print "$x == 9" if $x == 3*3;
2340
2341           There is now a "bsstr()" method to get the string in scientific
2342           notation aka 1e+2 instead of 100. Be advised that overloaded 'eq'
2343           always uses bstr() for comparison, but Perl represents some numbers
2344           as 100 and others as 1e+308.  If in doubt, convert both arguments
2345           to Math::BigInt before comparing them as strings:
2346
2347               use Test::More tests => 3;
2348               use Math::BigInt;
2349
2350               $x = Math::BigInt->new('1e56');
2351               $y = 1e56;
2352               is($x,$y);                     # fails
2353               is($x->bsstr(), $y);           # okay
2354               $y = Math::BigInt->new($y);
2355               is($x, $y);                    # okay
2356
2357           Alternatively, simply use "<=>" for comparisons, this always gets
2358           it right. There is not yet a way to get a number automatically
2359           represented as a string that matches exactly the way Perl
2360           represents it.
2361
2362           See also the section about "Infinity and Not a Number" for problems
2363           in comparing NaNs.
2364
2365       int()
2366           "int()" returns (at least for Perl v5.7.1 and up) another
2367           Math::BigInt, not a Perl scalar:
2368
2369               $x = Math::BigInt->new(123);
2370               $y = int($x);                           # 123 as a Math::BigInt
2371               $x = Math::BigFloat->new(123.45);
2372               $y = int($x);                           # 123 as a Math::BigFloat
2373
2374           If you want a real Perl scalar, use "numify()":
2375
2376               $y = $x->numify();                      # 123 as a scalar
2377
2378           This is seldom necessary, though, because this is done
2379           automatically, like when you access an array:
2380
2381               $z = $array[$x];                        # does work automatically
2382
2383       Modifying and =
2384           Beware of:
2385
2386               $x = Math::BigFloat->new(5);
2387               $y = $x;
2388
2389           This makes a second reference to the same object and stores it in
2390           $y. Thus anything that modifies $x (except overloaded operators)
2391           also modifies $y, and vice versa. Or in other words, "=" is only
2392           safe if you modify your Math::BigInt objects only via overloaded
2393           math. As soon as you use a method call it breaks:
2394
2395               $x->bmul(2);
2396               print "$x, $y\n";       # prints '10, 10'
2397
2398           If you want a true copy of $x, use:
2399
2400               $y = $x->copy();
2401
2402           You can also chain the calls like this, this first makes a copy and
2403           then multiply it by 2:
2404
2405               $y = $x->copy()->bmul(2);
2406
2407           See also the documentation for overload.pm regarding "=".
2408
2409       Overloading -$x
2410           The following:
2411
2412               $x = -$x;
2413
2414           is slower than
2415
2416               $x->bneg();
2417
2418           since overload calls "sub($x,0,1);" instead of "neg($x)". The first
2419           variant needs to preserve $x since it does not know that it later
2420           gets overwritten.  This makes a copy of $x and takes O(N), but
2421           $x->bneg() is O(1).
2422
2423       Mixing different object types
2424           With overloaded operators, it is the first (dominating) operand
2425           that determines which method is called. Here are some examples
2426           showing what actually gets called in various cases.
2427
2428               use Math::BigInt;
2429               use Math::BigFloat;
2430
2431               $mbf  = Math::BigFloat->new(5);
2432               $mbi2 = Math::BigInt->new(5);
2433               $mbi  = Math::BigInt->new(2);
2434                                               # what actually gets called:
2435               $float = $mbf + $mbi;           # $mbf->badd($mbi)
2436               $float = $mbf / $mbi;           # $mbf->bdiv($mbi)
2437               $integer = $mbi + $mbf;         # $mbi->badd($mbf)
2438               $integer = $mbi2 / $mbi;        # $mbi2->bdiv($mbi)
2439               $integer = $mbi2 / $mbf;        # $mbi2->bdiv($mbf)
2440
2441           For instance, Math::BigInt->bdiv() always returns a Math::BigInt,
2442           regardless of whether the second operant is a Math::BigFloat. To
2443           get a Math::BigFloat you either need to call the operation
2444           manually, make sure each operand already is a Math::BigFloat, or
2445           cast to that type via Math::BigFloat->new():
2446
2447               $float = Math::BigFloat->new($mbi2) / $mbi;     # = 2.5
2448
2449           Beware of casting the entire expression, as this would cast the
2450           result, at which point it is too late:
2451
2452               $float = Math::BigFloat->new($mbi2 / $mbi);     # = 2
2453
2454           Beware also of the order of more complicated expressions like:
2455
2456               $integer = ($mbi2 + $mbi) / $mbf;               # int / float => int
2457               $integer = $mbi2 / Math::BigFloat->new($mbi);   # ditto
2458
2459           If in doubt, break the expression into simpler terms, or cast all
2460           operands to the desired resulting type.
2461
2462           Scalar values are a bit different, since:
2463
2464               $float = 2 + $mbf;
2465               $float = $mbf + 2;
2466
2467           both result in the proper type due to the way the overloaded math
2468           works.
2469
2470           This section also applies to other overloaded math packages, like
2471           Math::String.
2472
2473           One solution to you problem might be autoupgrading|upgrading. See
2474           the pragmas bignum, bigint and bigrat for an easy way to do this.
2475

BUGS

2477       Please report any bugs or feature requests to "bug-math-bigint at
2478       rt.cpan.org", or through the web interface at
2479       <https://rt.cpan.org/Ticket/Create.html?Queue=Math-BigInt> (requires
2480       login).  We will be notified, and then you'll automatically be notified
2481       of progress on your bug as I make changes.
2482

SUPPORT

2484       You can find documentation for this module with the perldoc command.
2485
2486           perldoc Math::BigInt
2487
2488       You can also look for information at:
2489
2490       •   GitHub
2491
2492           <https://github.com/pjacklam/p5-Math-BigInt>
2493
2494       •   RT: CPAN's request tracker
2495
2496           <https://rt.cpan.org/Dist/Display.html?Name=Math-BigInt>
2497
2498       •   MetaCPAN
2499
2500           <https://metacpan.org/release/Math-BigInt>
2501
2502       •   CPAN Testers Matrix
2503
2504           <http://matrix.cpantesters.org/?dist=Math-BigInt>
2505
2506       •   CPAN Ratings
2507
2508           <https://cpanratings.perl.org/dist/Math-BigInt>
2509
2510       •   The Bignum mailing list
2511
2512           •   Post to mailing list
2513
2514               "bignum at lists.scsys.co.uk"
2515
2516           •   View mailing list
2517
2518               <http://lists.scsys.co.uk/pipermail/bignum/>
2519
2520           •   Subscribe/Unsubscribe
2521
2522               <http://lists.scsys.co.uk/cgi-bin/mailman/listinfo/bignum>
2523

LICENSE

2525       This program is free software; you may redistribute it and/or modify it
2526       under the same terms as Perl itself.
2527

SEE ALSO

2529       Math::BigFloat and Math::BigRat as well as the backends
2530       Math::BigInt::FastCalc, Math::BigInt::GMP, and Math::BigInt::Pari.
2531
2532       The pragmas bignum, bigint and bigrat also might be of interest because
2533       they solve the autoupgrading/downgrading issue, at least partly.
2534

AUTHORS

2536       •   Mark Biggar, overloaded interface by Ilya Zakharevich, 1996-2001.
2537
2538       •   Completely rewritten by Tels <http://bloodgate.com>, 2001-2008.
2539
2540       •   Florian Ragwitz <flora@cpan.org>, 2010.
2541
2542       •   Peter John Acklam <pjacklam@gmail.com>, 2011-.
2543
2544       Many people contributed in one or more ways to the final beast, see the
2545       file CREDITS for an (incomplete) list. If you miss your name, please
2546       drop me a mail. Thank you!
2547
2548
2549
2550perl v5.36.0                      2022-07-22                   Math::BigInt(3)
Impressum