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 or
288       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 if
641           $y supports the method as_number(). If it does, as_number() is
642           called. The method as_int() (and as_number()) is expected to return
643           either an object that has the same class as $x, a subclass thereof,
644           or a string that "ref($x)->new()" can parse to create an object.
645
646           as_number() is an alias to as_int(). "as_number" was introduced in
647           v1.22, while as_int() was introduced in v1.68.
648
649           In Math::BigInt, as_int() has the same effect as copy().
650
651       as_float()
652           Return the argument as a Math::BigFloat object.
653
654       as_rat()
655           Return the argument as a Math::BigRat object.
656
657   Boolean methods
658       None of these methods modify the invocand object.
659
660       is_zero()
661               $x->is_zero();              # true if $x is 0
662
663           Returns true if the invocand is zero and false otherwise.
664
665       is_one( [ SIGN ])
666               $x->is_one();               # true if $x is +1
667               $x->is_one("+");            # ditto
668               $x->is_one("-");            # true if $x is -1
669
670           Returns true if the invocand is one and false otherwise.
671
672       is_finite()
673               $x->is_finite();    # true if $x is not +inf, -inf or NaN
674
675           Returns true if the invocand is a finite number, i.e., it is
676           neither +inf, -inf, nor NaN.
677
678       is_inf( [ SIGN ] )
679               $x->is_inf();               # true if $x is +inf
680               $x->is_inf("+");            # ditto
681               $x->is_inf("-");            # true if $x is -inf
682
683           Returns true if the invocand is infinite and false otherwise.
684
685       is_nan()
686               $x->is_nan();               # true if $x is NaN
687
688       is_positive()
689       is_pos()
690               $x->is_positive();          # true if > 0
691               $x->is_pos();               # ditto
692
693           Returns true if the invocand is positive and false otherwise. A
694           "NaN" is neither positive nor negative.
695
696       is_negative()
697       is_neg()
698               $x->is_negative();          # true if < 0
699               $x->is_neg();               # ditto
700
701           Returns true if the invocand is negative and false otherwise. A
702           "NaN" is neither positive nor negative.
703
704       is_non_positive()
705               $x->is_non_positive();      # true if <= 0
706
707           Returns true if the invocand is negative or zero.
708
709       is_non_negative()
710               $x->is_non_negative();      # true if >= 0
711
712           Returns true if the invocand is positive or zero.
713
714       is_odd()
715               $x->is_odd();               # true if odd, false for even
716
717           Returns true if the invocand is odd and false otherwise. "NaN",
718           "+inf", and "-inf" are neither odd nor even.
719
720       is_even()
721               $x->is_even();              # true if $x is even
722
723           Returns true if the invocand is even and false otherwise. "NaN",
724           "+inf", "-inf" are not integers and are neither odd nor even.
725
726       is_int()
727               $x->is_int();               # true if $x is an integer
728
729           Returns true if the invocand is an integer and false otherwise.
730           "NaN", "+inf", "-inf" are not integers.
731
732   Comparison methods
733       None of these methods modify the invocand object. Note that a "NaN" is
734       neither less than, greater than, or equal to anything else, even a
735       "NaN".
736
737       bcmp()
738               $x->bcmp($y);
739
740           Returns -1, 0, 1 depending on whether $x is less than, equal to, or
741           grater than $y. Returns undef if any operand is a NaN.
742
743       bacmp()
744               $x->bacmp($y);
745
746           Returns -1, 0, 1 depending on whether the absolute value of $x is
747           less than, equal to, or grater than the absolute value of $y.
748           Returns undef if any operand is a NaN.
749
750       beq()
751               $x -> beq($y);
752
753           Returns true if and only if $x is equal to $y, and false otherwise.
754
755       bne()
756               $x -> bne($y);
757
758           Returns true if and only if $x is not equal to $y, and false
759           otherwise.
760
761       blt()
762               $x -> blt($y);
763
764           Returns true if and only if $x is equal to $y, and false otherwise.
765
766       ble()
767               $x -> ble($y);
768
769           Returns true if and only if $x is less than or equal to $y, and
770           false otherwise.
771
772       bgt()
773               $x -> bgt($y);
774
775           Returns true if and only if $x is greater than $y, and false
776           otherwise.
777
778       bge()
779               $x -> bge($y);
780
781           Returns true if and only if $x is greater than or equal to $y, and
782           false otherwise.
783
784   Arithmetic methods
785       These methods modify the invocand object and returns it.
786
787       bneg()
788               $x->bneg();
789
790           Negate the number, e.g. change the sign between '+' and '-', or
791           between '+inf' and '-inf', respectively. Does nothing for NaN or
792           zero.
793
794       babs()
795               $x->babs();
796
797           Set the number to its absolute value, e.g. change the sign from '-'
798           to '+' and from '-inf' to '+inf', respectively. Does nothing for
799           NaN or positive numbers.
800
801       bsgn()
802               $x->bsgn();
803
804           Signum function. Set the number to -1, 0, or 1, depending on
805           whether the number is negative, zero, or positive, respectively.
806           Does not modify NaNs.
807
808       bnorm()
809               $x->bnorm();                        # normalize (no-op)
810
811           Normalize the number. This is a no-op and is provided only for
812           backwards compatibility.
813
814       binc()
815               $x->binc();                 # increment x by 1
816
817       bdec()
818               $x->bdec();                 # decrement x by 1
819
820       badd()
821               $x->badd($y);               # addition (add $y to $x)
822
823       bsub()
824               $x->bsub($y);               # subtraction (subtract $y from $x)
825
826       bmul()
827               $x->bmul($y);               # multiplication (multiply $x by $y)
828
829       bmuladd()
830               $x->bmuladd($y,$z);
831
832           Multiply $x by $y, and then add $z to the result,
833
834           This method was added in v1.87 of Math::BigInt (June 2007).
835
836       bdiv()
837               $x->bdiv($y);               # divide, set $x to quotient
838
839           Divides $x by $y by doing floored division (F-division), where the
840           quotient is the floored (rounded towards negative infinity)
841           quotient of the two operands.  In list context, returns the
842           quotient and the remainder. The remainder is either zero or has the
843           same sign as the second operand. In scalar context, only the
844           quotient is returned.
845
846           The quotient is always the greatest integer less than or equal to
847           the real-valued quotient of the two operands, and the remainder
848           (when it is non-zero) always has the same sign as the second
849           operand; so, for example,
850
851                 1 /  4  => ( 0,  1)
852                 1 / -4  => (-1, -3)
853                -3 /  4  => (-1,  1)
854                -3 / -4  => ( 0, -3)
855               -11 /  2  => (-5,  1)
856                11 / -2  => (-5, -1)
857
858           The behavior of the overloaded operator % agrees with the behavior
859           of Perl's built-in % operator (as documented in the perlop
860           manpage), and the equation
861
862               $x == ($x / $y) * $y + ($x % $y)
863
864           holds true for any finite $x and finite, non-zero $y.
865
866           Perl's "use integer" might change the behaviour of % and / for
867           scalars. This is because under 'use integer' Perl does what the
868           underlying C library thinks is right, and this varies. However,
869           "use integer" does not change the way things are done with
870           Math::BigInt objects.
871
872       btdiv()
873               $x->btdiv($y);              # divide, set $x to quotient
874
875           Divides $x by $y by doing truncated division (T-division), where
876           quotient is the truncated (rouneded towards zero) quotient of the
877           two operands. In list context, returns the quotient and the
878           remainder. The remainder is either zero or has the same sign as the
879           first operand. In scalar context, only the quotient is returned.
880
881       bmod()
882               $x->bmod($y);               # modulus (x % y)
883
884           Returns $x modulo $y, i.e., the remainder after floored division
885           (F-division).  This method is like Perl's % operator. See "bdiv()".
886
887       btmod()
888               $x->btmod($y);              # modulus
889
890           Returns the remainer after truncated division (T-division). See
891           "btdiv()".
892
893       bmodinv()
894               $x->bmodinv($mod);          # modular multiplicative inverse
895
896           Returns the multiplicative inverse of $x modulo $mod. If
897
898               $y = $x -> copy() -> bmodinv($mod)
899
900           then $y is the number closest to zero, and with the same sign as
901           $mod, satisfying
902
903               ($x * $y) % $mod = 1 % $mod
904
905           If $x and $y are non-zero, they must be relative primes, i.e.,
906           "bgcd($y, $mod)==1". '"NaN"' is returned when no modular
907           multiplicative inverse exists.
908
909       bmodpow()
910               $num->bmodpow($exp,$mod);           # modular exponentiation
911                                                   # ($num**$exp % $mod)
912
913           Returns the value of $num taken to the power $exp in the modulus
914           $mod using binary exponentiation.  "bmodpow" is far superior to
915           writing
916
917               $num ** $exp % $mod
918
919           because it is much faster - it reduces internal variables into the
920           modulus whenever possible, so it operates on smaller numbers.
921
922           "bmodpow" also supports negative exponents.
923
924               bmodpow($num, -1, $mod)
925
926           is exactly equivalent to
927
928               bmodinv($num, $mod)
929
930       bpow()
931               $x->bpow($y);               # power of arguments (x ** y)
932
933           bpow() (and the rounding functions) now modifies the first argument
934           and returns it, unlike the old code which left it alone and only
935           returned the result. This is to be consistent with badd() etc. The
936           first three modifies $x, the last one won't:
937
938               print bpow($x,$i),"\n";         # modify $x
939               print $x->bpow($i),"\n";        # ditto
940               print $x **= $i,"\n";           # the same
941               print $x ** $i,"\n";            # leave $x alone
942
943           The form "$x **= $y" is faster than "$x = $x ** $y;", though.
944
945       blog()
946               $x->blog($base, $accuracy);         # logarithm of x to the base $base
947
948           If $base is not defined, Euler's number (e) is used:
949
950               print $x->blog(undef, 100);         # log(x) to 100 digits
951
952       bexp()
953               $x->bexp($accuracy);                # calculate e ** X
954
955           Calculates the expression "e ** $x" where "e" is Euler's number.
956
957           This method was added in v1.82 of Math::BigInt (April 2007).
958
959           See also "blog()".
960
961       bnok()
962               $x->bnok($y);               # x over y (binomial coefficient n over k)
963
964           Calculates the binomial coefficient n over k, also called the
965           "choose" function, which is
966
967               ( n )       n!
968               |   |  = --------
969               ( k )    k!(n-k)!
970
971           when n and k are non-negative. This method implements the full
972           Kronenburg extension (Kronenburg, M.J. "The Binomial Coefficient
973           for Negative Arguments."  18 May 2011.
974           http://arxiv.org/abs/1105.3689/) illustrated by the following
975           pseudo-code:
976
977               if n >= 0 and k >= 0:
978                   return binomial(n, k)
979               if k >= 0:
980                   return (-1)^k*binomial(-n+k-1, k)
981               if k <= n:
982                   return (-1)^(n-k)*binomial(-k-1, n-k)
983               else
984                   return 0
985
986           The behaviour is identical to the behaviour of the Maple and
987           Mathematica function for negative integers n, k.
988
989       buparrow()
990       uparrow()
991               $a -> buparrow($n, $b);         # modifies $a
992               $x = $a -> uparrow($n, $b);     # does not modify $a
993
994           This method implements Knuth's up-arrow notation, where $n is a
995           non-negative integer representing the number of up-arrows. $n = 0
996           gives multiplication, $n = 1 gives exponentiation, $n = 2 gives
997           tetration, $n = 3 gives hexation etc. The following illustrates the
998           relation between the first values of $n.
999
1000           See <https://en.wikipedia.org/wiki/Knuth%27s_up-arrow_notation>.
1001
1002       backermann()
1003       ackermann()
1004               $m -> backermann($n);           # modifies $a
1005               $x = $m -> ackermann($n);       # does not modify $a
1006
1007           This method implements the Ackermann function:
1008
1009                        / n + 1              if m = 0
1010              A(m, n) = | A(m-1, 1)          if m > 0 and n = 0
1011                        \ A(m-1, A(m, n-1))  if m > 0 and n > 0
1012
1013           Its value grows rapidly, even for small inputs. For example, A(4,
1014           2) is an integer of 19729 decimal digits.
1015
1016           See https://en.wikipedia.org/wiki/Ackermann_function
1017
1018       bsin()
1019               my $x = Math::BigInt->new(1);
1020               print $x->bsin(100), "\n";
1021
1022           Calculate the sine of $x, modifying $x in place.
1023
1024           In Math::BigInt, unless upgrading is in effect, the result is
1025           truncated to an integer.
1026
1027           This method was added in v1.87 of Math::BigInt (June 2007).
1028
1029       bcos()
1030               my $x = Math::BigInt->new(1);
1031               print $x->bcos(100), "\n";
1032
1033           Calculate the cosine of $x, modifying $x in place.
1034
1035           In Math::BigInt, unless upgrading is in effect, the result is
1036           truncated to an integer.
1037
1038           This method was added in v1.87 of Math::BigInt (June 2007).
1039
1040       batan()
1041               my $x = Math::BigFloat->new(0.5);
1042               print $x->batan(100), "\n";
1043
1044           Calculate the arcus tangens of $x, modifying $x in place.
1045
1046           In Math::BigInt, unless upgrading is in effect, the result is
1047           truncated to an integer.
1048
1049           This method was added in v1.87 of Math::BigInt (June 2007).
1050
1051       batan2()
1052               my $x = Math::BigInt->new(1);
1053               my $y = Math::BigInt->new(1);
1054               print $y->batan2($x), "\n";
1055
1056           Calculate the arcus tangens of $y divided by $x, modifying $y in
1057           place.
1058
1059           In Math::BigInt, unless upgrading is in effect, the result is
1060           truncated to an integer.
1061
1062           This method was added in v1.87 of Math::BigInt (June 2007).
1063
1064       bsqrt()
1065               $x->bsqrt();                # calculate square root
1066
1067           bsqrt() returns the square root truncated to an integer.
1068
1069           If you want a better approximation of the square root, then use:
1070
1071               $x = Math::BigFloat->new(12);
1072               Math::BigFloat->precision(0);
1073               Math::BigFloat->round_mode('even');
1074               print $x->copy->bsqrt(),"\n";           # 4
1075
1076               Math::BigFloat->precision(2);
1077               print $x->bsqrt(),"\n";                 # 3.46
1078               print $x->bsqrt(3),"\n";                # 3.464
1079
1080       broot()
1081               $x->broot($N);
1082
1083           Calculates the N'th root of $x.
1084
1085       bfac()
1086               $x->bfac();             # factorial of $x
1087
1088           Returns the factorial of $x, i.e., $x*($x-1)*($x-2)*...*2*1, the
1089           product of all positive integers up to and including $x. $x must be
1090           > -1. The factorial of N is commonly written as N!, or N!1, when
1091           using the multifactorial notation.
1092
1093       bdfac()
1094               $x->bdfac();                # double factorial of $x
1095
1096           Returns the double factorial of $x, i.e., $x*($x-2)*($x-4)*... $x
1097           must be > -2. The double factorial of N is commonly written as N!!,
1098           or N!2, when using the multifactorial notation.
1099
1100       btfac()
1101               $x->btfac();            # triple factorial of $x
1102
1103           Returns the triple factorial of $x, i.e., $x*($x-3)*($x-6)*... $x
1104           must be > -3. The triple factorial of N is commonly written as
1105           N!!!, or N!3, when using the multifactorial notation.
1106
1107       bmfac()
1108               $x->bmfac($k);          # $k'th multifactorial of $x
1109
1110           Returns the multi-factorial of $x, i.e., $x*($x-$k)*($x-2*$k)*...
1111           $x must be > -$k. The multi-factorial of N is commonly written as
1112           N!K.
1113
1114       bfib()
1115               $F = $n->bfib();            # a single Fibonacci number
1116               @F = $n->bfib();            # a list of Fibonacci numbers
1117
1118           In scalar context, returns a single Fibonacci number. In list
1119           context, returns a list of Fibonacci numbers. The invocand is the
1120           last element in the output.
1121
1122           The Fibonacci sequence is defined by
1123
1124               F(0) = 0
1125               F(1) = 1
1126               F(n) = F(n-1) + F(n-2)
1127
1128           In list context, F(0) and F(n) is the first and last number in the
1129           output, respectively. For example, if $n is 12, then "@F =
1130           $n->bfib()" returns the following values, F(0) to F(12):
1131
1132               0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144
1133
1134           The sequence can also be extended to negative index n using the re-
1135           arranged recurrence relation
1136
1137               F(n-2) = F(n) - F(n-1)
1138
1139           giving the bidirectional sequence
1140
1141                  n  -7  -6  -5  -4  -3  -2  -1   0   1   2   3   4   5   6   7
1142               F(n)  13  -8   5  -3   2  -1   1   0   1   1   2   3   5   8  13
1143
1144           If $n is -12, the following values, F(0) to F(12), are returned:
1145
1146               0, 1, -1, 2, -3, 5, -8, 13, -21, 34, -55, 89, -144
1147
1148       blucas()
1149               $F = $n->blucas();          # a single Lucas number
1150               @F = $n->blucas();          # a list of Lucas numbers
1151
1152           In scalar context, returns a single Lucas number. In list context,
1153           returns a list of Lucas numbers. The invocand is the last element
1154           in the output.
1155
1156           The Lucas sequence is defined by
1157
1158               L(0) = 2
1159               L(1) = 1
1160               L(n) = L(n-1) + L(n-2)
1161
1162           In list context, L(0) and L(n) is the first and last number in the
1163           output, respectively. For example, if $n is 12, then "@L =
1164           $n->blucas()" returns the following values, L(0) to L(12):
1165
1166               2, 1, 3, 4, 7, 11, 18, 29, 47, 76, 123, 199, 322
1167
1168           The sequence can also be extended to negative index n using the re-
1169           arranged recurrence relation
1170
1171               L(n-2) = L(n) - L(n-1)
1172
1173           giving the bidirectional sequence
1174
1175                  n  -7  -6  -5  -4  -3  -2  -1   0   1   2   3   4   5   6   7
1176               L(n)  29 -18  11  -7   4  -3   1   2   1   3   4   7  11  18  29
1177
1178           If $n is -12, the following values, L(0) to L(-12), are returned:
1179
1180               2, 1, -3, 4, -7, 11, -18, 29, -47, 76, -123, 199, -322
1181
1182       brsft()
1183               $x->brsft($n);              # right shift $n places in base 2
1184               $x->brsft($n, $b);          # right shift $n places in base $b
1185
1186           The latter is equivalent to
1187
1188               $x -> bdiv($b -> copy() -> bpow($n))
1189
1190       blsft()
1191               $x->blsft($n);              # left shift $n places in base 2
1192               $x->blsft($n, $b);          # left shift $n places in base $b
1193
1194           The latter is equivalent to
1195
1196               $x -> bmul($b -> copy() -> bpow($n))
1197
1198   Bitwise methods
1199       band()
1200               $x->band($y);               # bitwise and
1201
1202       bior()
1203               $x->bior($y);               # bitwise inclusive or
1204
1205       bxor()
1206               $x->bxor($y);               # bitwise exclusive or
1207
1208       bnot()
1209               $x->bnot();                 # bitwise not (two's complement)
1210
1211           Two's complement (bitwise not). This is equivalent to, but faster
1212           than,
1213
1214               $x->binc()->bneg();
1215
1216   Rounding methods
1217       round()
1218               $x->round($A,$P,$round_mode);
1219
1220           Round $x to accuracy $A or precision $P using the round mode
1221           $round_mode.
1222
1223       bround()
1224               $x->bround($N);               # accuracy: preserve $N digits
1225
1226           Rounds $x to an accuracy of $N digits.
1227
1228       bfround()
1229               $x->bfround($N);
1230
1231           Rounds to a multiple of 10**$N. Examples:
1232
1233               Input            N          Result
1234
1235               123456.123456    3          123500
1236               123456.123456    2          123450
1237               123456.123456   -2          123456.12
1238               123456.123456   -3          123456.123
1239
1240       bfloor()
1241               $x->bfloor();
1242
1243           Round $x towards minus infinity, i.e., set $x to the largest
1244           integer less than or equal to $x.
1245
1246       bceil()
1247               $x->bceil();
1248
1249           Round $x towards plus infinity, i.e., set $x to the smallest
1250           integer greater than or equal to $x).
1251
1252       bint()
1253               $x->bint();
1254
1255           Round $x towards zero.
1256
1257   Other mathematical methods
1258       bgcd()
1259               $x -> bgcd($y);             # GCD of $x and $y
1260               $x -> bgcd($y, $z, ...);    # GCD of $x, $y, $z, ...
1261
1262           Returns the greatest common divisor (GCD).
1263
1264       blcm()
1265               $x -> blcm($y);             # LCM of $x and $y
1266               $x -> blcm($y, $z, ...);    # LCM of $x, $y, $z, ...
1267
1268           Returns the least common multiple (LCM).
1269
1270   Object property methods
1271       sign()
1272               $x->sign();
1273
1274           Return the sign, of $x, meaning either "+", "-", "-inf", "+inf" or
1275           NaN.
1276
1277           If you want $x to have a certain sign, use one of the following
1278           methods:
1279
1280               $x->babs();                 # '+'
1281               $x->babs()->bneg();         # '-'
1282               $x->bnan();                 # 'NaN'
1283               $x->binf();                 # '+inf'
1284               $x->binf('-');              # '-inf'
1285
1286       digit()
1287               $x->digit($n);       # return the nth digit, counting from right
1288
1289           If $n is negative, returns the digit counting from left.
1290
1291       digitsum()
1292               $x->digitsum();
1293
1294           Computes the sum of the base 10 digits and returns it.
1295
1296       bdigitsum()
1297               $x->bdigitsum();
1298
1299           Computes the sum of the base 10 digits and assigns the result to
1300           the invocand.
1301
1302       length()
1303               $x->length();
1304               ($xl, $fl) = $x->length();
1305
1306           Returns the number of digits in the decimal representation of the
1307           number. In list context, returns the length of the integer and
1308           fraction part. For Math::BigInt objects, the length of the fraction
1309           part is always 0.
1310
1311           The following probably doesn't do what you expect:
1312
1313               $c = Math::BigInt->new(123);
1314               print $c->length(),"\n";                # prints 30
1315
1316           It prints both the number of digits in the number and in the
1317           fraction part since print calls length() in list context. Use
1318           something like:
1319
1320               print scalar $c->length(),"\n";         # prints 3
1321
1322       mantissa()
1323               $x->mantissa();
1324
1325           Return the signed mantissa of $x as a Math::BigInt.
1326
1327       exponent()
1328               $x->exponent();
1329
1330           Return the exponent of $x as a Math::BigInt.
1331
1332       parts()
1333               $x->parts();
1334
1335           Returns the significand (mantissa) and the exponent as integers. In
1336           Math::BigFloat, both are returned as Math::BigInt objects.
1337
1338       sparts()
1339           Returns the significand (mantissa) and the exponent as integers. In
1340           scalar context, only the significand is returned. The significand
1341           is the integer with the smallest absolute value. The output of
1342           sparts() corresponds to the output from bsstr().
1343
1344           In Math::BigInt, this method is identical to parts().
1345
1346       nparts()
1347           Returns the significand (mantissa) and exponent corresponding to
1348           normalized notation. In scalar context, only the significand is
1349           returned. For finite non-zero numbers, the significand's absolute
1350           value is greater than or equal to 1 and less than 10. The output of
1351           nparts() corresponds to the output from bnstr(). In Math::BigInt,
1352           if the significand can not be represented as an integer, upgrading
1353           is performed or NaN is returned.
1354
1355       eparts()
1356           Returns the significand (mantissa) and exponent corresponding to
1357           engineering notation. In scalar context, only the significand is
1358           returned. For finite non-zero numbers, the significand's absolute
1359           value is greater than or equal to 1 and less than 1000, and the
1360           exponent is a multiple of 3. The output of eparts() corresponds to
1361           the output from bestr(). In Math::BigInt, if the significand can
1362           not be represented as an integer, upgrading is performed or NaN is
1363           returned.
1364
1365       dparts()
1366           Returns the integer part and the fraction part. If the fraction
1367           part can not be represented as an integer, upgrading is performed
1368           or NaN is returned. The output of dparts() corresponds to the
1369           output from bdstr().
1370
1371       fparts()
1372           Returns the smallest possible numerator and denominator so that the
1373           numerator divided by the denominator gives back the original value.
1374           For finite numbers, both values are integers. Mnemonic: fraction.
1375
1376       numerator()
1377           Together with "denominator()", returns the smallest integers so
1378           that the numerator divided by the denominator reproduces the
1379           original value. With Math::BigInt, numerator() simply returns a
1380           copy of the invocand.
1381
1382       denominator()
1383           Together with "numerator()", returns the smallest integers so that
1384           the numerator divided by the denominator reproduces the original
1385           value. With Math::BigInt, denominator() always returns either a 1
1386           or a NaN.
1387
1388   String conversion methods
1389       bstr()
1390           Returns a string representing the number using decimal notation. In
1391           Math::BigFloat, the output is zero padded according to the current
1392           accuracy or precision, if any of those are defined.
1393
1394       bsstr()
1395           Returns a string representing the number using scientific notation
1396           where both the significand (mantissa) and the exponent are
1397           integers. The output corresponds to the output from sparts().
1398
1399                 123 is returned as "123e+0"
1400                1230 is returned as "123e+1"
1401               12300 is returned as "123e+2"
1402               12000 is returned as "12e+3"
1403               10000 is returned as "1e+4"
1404
1405       bnstr()
1406           Returns a string representing the number using normalized notation,
1407           the most common variant of scientific notation. For finite non-zero
1408           numbers, the absolute value of the significand is greater than or
1409           equal to 1 and less than 10. The output corresponds to the output
1410           from nparts().
1411
1412                 123 is returned as "1.23e+2"
1413                1230 is returned as "1.23e+3"
1414               12300 is returned as "1.23e+4"
1415               12000 is returned as "1.2e+4"
1416               10000 is returned as "1e+4"
1417
1418       bestr()
1419           Returns a string representing the number using engineering
1420           notation. For finite non-zero numbers, the absolute value of the
1421           significand is greater than or equal to 1 and less than 1000, and
1422           the exponent is a multiple of 3. The output corresponds to the
1423           output from eparts().
1424
1425                 123 is returned as "123e+0"
1426                1230 is returned as "1.23e+3"
1427               12300 is returned as "12.3e+3"
1428               12000 is returned as "12e+3"
1429               10000 is returned as "10e+3"
1430
1431       bdstr()
1432           Returns a string representing the number using decimal notation.
1433           The output corresponds to the output from dparts().
1434
1435                 123 is returned as "123"
1436                1230 is returned as "1230"
1437               12300 is returned as "12300"
1438               12000 is returned as "12000"
1439               10000 is returned as "10000"
1440
1441       bfstr()
1442           Returns a string representing the number using fractional notation.
1443           The output corresponds to the output from fparts().
1444
1445                   12.345 is returned as "2469/200"
1446                  123.45 is returned as "2469/20"
1447                 1234.5 is returned as "2469/2"
1448                12345 is returned as "12345"
1449               123450 is returned as "123450"
1450
1451       to_hex()
1452               $x->to_hex();
1453
1454           Returns a hexadecimal string representation of the number. See also
1455           from_hex().
1456
1457       to_bin()
1458               $x->to_bin();
1459
1460           Returns a binary string representation of the number. See also
1461           from_bin().
1462
1463       to_oct()
1464               $x->to_oct();
1465
1466           Returns an octal string representation of the number. See also
1467           from_oct().
1468
1469       to_bytes()
1470               $x = Math::BigInt->new("1667327589");
1471               $s = $x->to_bytes();                    # $s = "cafe"
1472
1473           Returns a byte string representation of the number using big endian
1474           byte order.  The invocand must be a non-negative, finite integer.
1475           See also from_bytes().
1476
1477       to_base()
1478               $x = Math::BigInt->new("250");
1479               $x->to_base(2);     # returns "11111010"
1480               $x->to_base(8);     # returns "372"
1481               $x->to_base(16);    # returns "fa"
1482
1483           Returns a string representation of the number in the given base. If
1484           a collation sequence is given, the collation sequence determines
1485           which characters are used in the output.
1486
1487           Here are some more examples
1488
1489               $x = Math::BigInt->new("16")->to_base(3);       # returns "121"
1490               $x = Math::BigInt->new("44027")->to_base(36);   # returns "XYZ"
1491               $x = Math::BigInt->new("58314")->to_base(42);   # returns "Why"
1492               $x = Math::BigInt->new("4")->to_base(2, "-|");  # returns "|--"
1493
1494           See from_base() for information and examples.
1495
1496       to_base_num()
1497           Converts the given number to the given base. This method is
1498           equivalent to _to_base(), but returns numbers in an array rather
1499           than characters in a string. In the output, the first element is
1500           the most significant. Unlike _to_base(), all input values may be
1501           arbitrarily large.
1502
1503               $x = Math::BigInt->new(13);
1504               $x->to_base_num(2);                         # returns [1, 1, 0, 1]
1505
1506               $x = Math::BigInt->new(65191);
1507               $x->to_base_num(128);                       # returns [3, 125, 39]
1508
1509       as_hex()
1510               $x->as_hex();
1511
1512           As, to_hex(), but with a "0x" prefix.
1513
1514       as_bin()
1515               $x->as_bin();
1516
1517           As, to_bin(), but with a "0b" prefix.
1518
1519       as_oct()
1520               $x->as_oct();
1521
1522           As, to_oct(), but with a "0" prefix.
1523
1524       as_bytes()
1525           This is just an alias for to_bytes().
1526
1527   Other conversion methods
1528       numify()
1529               print $x->numify();
1530
1531           Returns a Perl scalar from $x. It is used automatically whenever a
1532           scalar is needed, for instance in array index operations.
1533
1534   Utility methods
1535       These utility methods are made public
1536
1537       dec_str_to_dec_flt_str()
1538           Takes a string representing any valid number using decimal notation
1539           and converts it to a string representing the same number using
1540           decimal floating point notation. The output consists of five parts
1541           joined together: the sign of the significand, the absolute value of
1542           the significand as the smallest possible integer, the letter "e",
1543           the sign of the exponent, and the absolute value of the exponent.
1544           If the input is invalid, nothing is returned.
1545
1546               $str2 = $class -> dec_str_to_dec_flt_str($str1);
1547
1548           Some examples
1549
1550               Input           Output
1551               31400.00e-4     +314e-2
1552               -0.00012300e8   -123e+2
1553               0               +0e+0
1554
1555       hex_str_to_dec_flt_str()
1556           Takes a string representing any valid number using hexadecimal
1557           notation and converts it to a string representing the same number
1558           using decimal floating point notation. The output has the same
1559           format as that of "dec_str_to_dec_flt_str()".
1560
1561               $str2 = $class -> hex_str_to_dec_flt_str($str1);
1562
1563           Some examples
1564
1565               Input           Output
1566               0xff            +255e+0
1567
1568           Some examples
1569
1570       oct_str_to_dec_flt_str()
1571           Takes a string representing any valid number using octal notation
1572           and converts it to a string representing the same number using
1573           decimal floating point notation. The output has the same format as
1574           that of "dec_str_to_dec_flt_str()".
1575
1576               $str2 = $class -> oct_str_to_dec_flt_str($str1);
1577
1578       bin_str_to_dec_flt_str()
1579           Takes a string representing any valid number using binary notation
1580           and converts it to a string representing the same number using
1581           decimal floating point notation. The output has the same format as
1582           that of "dec_str_to_dec_flt_str()".
1583
1584               $str2 = $class -> bin_str_to_dec_flt_str($str1);
1585
1586       dec_str_to_dec_str()
1587           Takes a string representing any valid number using decimal notation
1588           and converts it to a string representing the same number using
1589           decimal notation. If the number represents an integer, the output
1590           consists of a sign and the absolute value. If the number represents
1591           a non-integer, the output consists of a sign, the integer part of
1592           the number, the decimal point ".", and the fraction part of the
1593           number without any trailing zeros. If the input is invalid, nothing
1594           is returned.
1595
1596       hex_str_to_dec_str()
1597           Takes a string representing any valid number using hexadecimal
1598           notation and converts it to a string representing the same number
1599           using decimal notation. The output has the same format as that of
1600           "dec_str_to_dec_str()".
1601
1602       oct_str_to_dec_str()
1603           Takes a string representing any valid number using octal notation
1604           and converts it to a string representing the same number using
1605           decimal notation. The output has the same format as that of
1606           "dec_str_to_dec_str()".
1607
1608       bin_str_to_dec_str()
1609           Takes a string representing any valid number using binary notation
1610           and converts it to a string representing the same number using
1611           decimal notation. The output has the same format as that of
1612           "dec_str_to_dec_str()".
1613

ACCURACY and PRECISION

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

Infinity and Not a Number

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

INTERNALS

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

EXAMPLES

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

NUMERIC LITERALS

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

PERFORMANCE

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

SUBCLASSING

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

UPGRADING

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

EXPORTS

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

CAVEATS

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

BUGS

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

SUPPORT

2483       You can find documentation for this module with the perldoc command.
2484
2485           perldoc Math::BigInt
2486
2487       You can also look for information at:
2488
2489       •   GitHub
2490
2491           <https://github.com/pjacklam/p5-Math-BigInt>
2492
2493       •   RT: CPAN's request tracker
2494
2495           <https://rt.cpan.org/Dist/Display.html?Name=Math-BigInt>
2496
2497       •   MetaCPAN
2498
2499           <https://metacpan.org/release/Math-BigInt>
2500
2501       •   CPAN Testers Matrix
2502
2503           <http://matrix.cpantesters.org/?dist=Math-BigInt>
2504

LICENSE

2506       This program is free software; you may redistribute it and/or modify it
2507       under the same terms as Perl itself.
2508

SEE ALSO

2510       Math::BigFloat and Math::BigRat as well as the backends
2511       Math::BigInt::FastCalc, Math::BigInt::GMP, and Math::BigInt::Pari.
2512
2513       The pragmas bignum, bigint and bigrat also might be of interest because
2514       they solve the autoupgrading/downgrading issue, at least partly.
2515

AUTHORS

2517       •   Mark Biggar, overloaded interface by Ilya Zakharevich, 1996-2001.
2518
2519       •   Completely rewritten by Tels <http://bloodgate.com>, 2001-2008.
2520
2521       •   Florian Ragwitz <flora@cpan.org>, 2010.
2522
2523       •   Peter John Acklam <pjacklam@gmail.com>, 2011-.
2524
2525       Many people contributed in one or more ways to the final beast, see the
2526       file CREDITS for an (incomplete) list. If you miss your name, please
2527       drop me a mail. Thank you!
2528
2529
2530
2531perl v5.36.1                      2023-07-17                   Math::BigInt(3)
Impressum