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

NAME

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

DESCRIPTION

202       Math::BigInt provides support for arbitrary precision integers.
203       Overloading is also provided for Perl operators.
204
205   Input
206       Input values to these routines may be any scalar number or string that
207       looks like a number and represents an integer.
208
209       •   Leading and trailing whitespace is ignored.
210
211       •   Leading zeros are ignored.
212
213       •   If the string has a "0x" prefix, it is interpreted as a hexadecimal
214           number.
215
216       •   If the string has a "0o" prefix, it is interpreted as an octal
217           number.
218
219       •   If the string has a "0b" prefix, it is interpreted as a binary
220           number.
221
222       •   One underline is allowed between any two digits.
223
224       •   If the string can not be interpreted, NaN is returned.
225
226       Some examples of valid string input
227
228           Input string                Resulting value
229           123                         123
230           1.23e2                      123
231           12300e-2                    123
232           0xcafe                      51966
233           0XCAFE                      51966
234           0o1337                      735
235           0O1337                      735
236           0b1101                      13
237           0B1101                      13
238           67_538_754                  67538754
239           -4_5_6.7_8_9e+0_1_0         -4567890000000
240
241       Input given as scalar numbers might lose precision. Quote your input to
242       ensure that no digits are lost:
243
244           $x = Math::BigInt->new( 56789012345678901234 );   # bad
245           $x = Math::BigInt->new('56789012345678901234');   # good
246
247       Currently, Math::BigInt->new() defaults to 0, while
248       Math::BigInt->new('') results in 'NaN'. This might change in the
249       future, so use always the following explicit forms to get a zero or
250       NaN:
251
252           $zero = Math::BigInt->bzero();
253           $nan  = Math::BigInt->bnan();
254
255   Output
256       Output values are usually Math::BigInt objects.
257
258       Boolean operators "is_zero()", "is_one()", "is_inf()", etc. return true
259       or false.
260
261       Comparison operators "bcmp()" and "bacmp()") return -1, 0, 1, or undef.
262

METHODS

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

ACCURACY and PRECISION

1458       Math::BigInt and Math::BigFloat have full support for accuracy and
1459       precision based rounding, both automatically after every operation, as
1460       well as manually.
1461
1462       This section describes the accuracy/precision handling in Math::BigInt
1463       and Math::BigFloat as it used to be and as it is now, complete with an
1464       explanation of all terms and abbreviations.
1465
1466       Not yet implemented things (but with correct description) are marked
1467       with '!', things that need to be answered are marked with '?'.
1468
1469       In the next paragraph follows a short description of terms used here
1470       (because these may differ from terms used by others people or
1471       documentation).
1472
1473       During the rest of this document, the shortcuts A (for accuracy), P
1474       (for precision), F (fallback) and R (rounding mode) are be used.
1475
1476   Precision P
1477       Precision is a fixed number of digits before (positive) or after
1478       (negative) the decimal point. For example, 123.45 has a precision of
1479       -2. 0 means an integer like 123 (or 120). A precision of 2 means at
1480       least two digits to the left of the decimal point are zero, so 123 with
1481       P = 1 becomes 120. Note that numbers with zeros before the decimal
1482       point may have different precisions, because 1200 can have P = 0, 1 or
1483       2 (depending on what the initial value was). It could also have p < 0,
1484       when the digits after the decimal point are zero.
1485
1486       The string output (of floating point numbers) is padded with zeros:
1487
1488           Initial value    P      A       Result          String
1489           ------------------------------------------------------------
1490           1234.01         -3              1000            1000
1491           1234            -2              1200            1200
1492           1234.5          -1              1230            1230
1493           1234.001         1              1234            1234.0
1494           1234.01          0              1234            1234
1495           1234.01          2              1234.01         1234.01
1496           1234.01          5              1234.01         1234.01000
1497
1498       For Math::BigInt objects, no padding occurs.
1499
1500   Accuracy A
1501       Number of significant digits. Leading zeros are not counted. A number
1502       may have an accuracy greater than the non-zero digits when there are
1503       zeros in it or trailing zeros. For example, 123.456 has A of 6, 10203
1504       has 5, 123.0506 has 7, 123.45000 has 8 and 0.000123 has 3.
1505
1506       The string output (of floating point numbers) is padded with zeros:
1507
1508           Initial value    P      A       Result          String
1509           ------------------------------------------------------------
1510           1234.01                 3       1230            1230
1511           1234.01                 6       1234.01         1234.01
1512           1234.1                  8       1234.1          1234.1000
1513
1514       For Math::BigInt objects, no padding occurs.
1515
1516   Fallback F
1517       When both A and P are undefined, this is used as a fallback accuracy
1518       when dividing numbers.
1519
1520   Rounding mode R
1521       When rounding a number, different 'styles' or 'kinds' of rounding are
1522       possible.  (Note that random rounding, as in Math::Round, is not
1523       implemented.)
1524
1525       Directed rounding
1526
1527       These round modes always round in the same direction.
1528
1529       'trunc'
1530           Round towards zero. Remove all digits following the rounding place,
1531           i.e., replace them with zeros. Thus, 987.65 rounded to tens (P=1)
1532           becomes 980, and rounded to the fourth significant digit becomes
1533           987.6 (A=4). 123.456 rounded to the second place after the decimal
1534           point (P=-2) becomes 123.46. This corresponds to the IEEE 754
1535           rounding mode 'roundTowardZero'.
1536
1537       Rounding to nearest
1538
1539       These rounding modes round to the nearest digit. They differ in how
1540       they determine which way to round in the ambiguous case when there is a
1541       tie.
1542
1543       'even'
1544           Round towards the nearest even digit, e.g., when rounding to
1545           nearest integer, -5.5 becomes -6, 4.5 becomes 4, but 4.501 becomes
1546           5. This corresponds to the IEEE 754 rounding mode
1547           'roundTiesToEven'.
1548
1549       'odd'
1550           Round towards the nearest odd digit, e.g., when rounding to nearest
1551           integer, 4.5 becomes 5, -5.5 becomes -5, but 5.501 becomes 6. This
1552           corresponds to the IEEE 754 rounding mode 'roundTiesToOdd'.
1553
1554       '+inf'
1555           Round towards plus infinity, i.e., always round up. E.g., when
1556           rounding to the nearest integer, 4.5 becomes 5, -5.5 becomes -5,
1557           and 4.501 also becomes 5. This corresponds to the IEEE 754 rounding
1558           mode 'roundTiesToPositive'.
1559
1560       '-inf'
1561           Round towards minus infinity, i.e., always round down. E.g., when
1562           rounding to the nearest integer, 4.5 becomes 4, -5.5 becomes -6,
1563           but 4.501 becomes 5. This corresponds to the IEEE 754 rounding mode
1564           'roundTiesToNegative'.
1565
1566       'zero'
1567           Round towards zero, i.e., round positive numbers down and negative
1568           numbers up.  E.g., when rounding to the nearest integer, 4.5
1569           becomes 4, -5.5 becomes -5, but 4.501 becomes 5. This corresponds
1570           to the IEEE 754 rounding mode 'roundTiesToZero'.
1571
1572       'common'
1573           Round away from zero, i.e., round to the number with the largest
1574           absolute value. E.g., when rounding to the nearest integer, -1.5
1575           becomes -2, 1.5 becomes 2 and 1.49 becomes 1. This corresponds to
1576           the IEEE 754 rounding mode 'roundTiesToAway'.
1577
1578       The handling of A & P in MBI/MBF (the old core code shipped with Perl
1579       versions <= 5.7.2) is like this:
1580
1581       Precision
1582             * bfround($p) is able to round to $p number of digits after the decimal
1583               point
1584             * otherwise P is unused
1585
1586       Accuracy (significant digits)
1587             * bround($a) rounds to $a significant digits
1588             * only bdiv() and bsqrt() take A as (optional) parameter
1589               + other operations simply create the same number (bneg etc), or
1590                 more (bmul) of digits
1591               + rounding/truncating is only done when explicitly calling one
1592                 of bround or bfround, and never for Math::BigInt (not implemented)
1593             * bsqrt() simply hands its accuracy argument over to bdiv.
1594             * the documentation and the comment in the code indicate two
1595               different ways on how bdiv() determines the maximum number
1596               of digits it should calculate, and the actual code does yet
1597               another thing
1598               POD:
1599                 max($Math::BigFloat::div_scale,length(dividend)+length(divisor))
1600               Comment:
1601                 result has at most max(scale, length(dividend), length(divisor)) digits
1602               Actual code:
1603                 scale = max(scale, length(dividend)-1,length(divisor)-1);
1604                 scale += length(divisor) - length(dividend);
1605               So for lx = 3, ly = 9, scale = 10, scale will actually be 16 (10
1606               So for lx = 3, ly = 9, scale = 10, scale will actually be 16
1607               (10+9-3). Actually, the 'difference' added to the scale is cal-
1608               culated from the number of "significant digits" in dividend and
1609               divisor, which is derived by looking at the length of the man-
1610               tissa. Which is wrong, since it includes the + sign (oops) and
1611               actually gets 2 for '+100' and 4 for '+101'. Oops again. Thus
1612               124/3 with div_scale=1 will get you '41.3' based on the strange
1613               assumption that 124 has 3 significant digits, while 120/7 will
1614               get you '17', not '17.1' since 120 is thought to have 2 signif-
1615               icant digits. The rounding after the division then uses the
1616               remainder and $y to determine whether it must round up or down.
1617            ?  I have no idea which is the right way. That's why I used a slightly more
1618            ?  simple scheme and tweaked the few failing testcases to match it.
1619
1620       This is how it works now:
1621
1622       Setting/Accessing
1623             * You can set the A global via Math::BigInt->accuracy() or
1624               Math::BigFloat->accuracy() or whatever class you are using.
1625             * You can also set P globally by using Math::SomeClass->precision()
1626               likewise.
1627             * Globals are classwide, and not inherited by subclasses.
1628             * to undefine A, use Math::SomeCLass->accuracy(undef);
1629             * to undefine P, use Math::SomeClass->precision(undef);
1630             * Setting Math::SomeClass->accuracy() clears automatically
1631               Math::SomeClass->precision(), and vice versa.
1632             * To be valid, A must be > 0, P can have any value.
1633             * If P is negative, this means round to the P'th place to the right of the
1634               decimal point; positive values mean to the left of the decimal point.
1635               P of 0 means round to integer.
1636             * to find out the current global A, use Math::SomeClass->accuracy()
1637             * to find out the current global P, use Math::SomeClass->precision()
1638             * use $x->accuracy() respective $x->precision() for the local
1639               setting of $x.
1640             * Please note that $x->accuracy() respective $x->precision()
1641               return eventually defined global A or P, when $x's A or P is not
1642               set.
1643
1644       Creating numbers
1645             * When you create a number, you can give the desired A or P via:
1646               $x = Math::BigInt->new($number,$A,$P);
1647             * Only one of A or P can be defined, otherwise the result is NaN
1648             * If no A or P is give ($x = Math::BigInt->new($number) form), then the
1649               globals (if set) will be used. Thus changing the global defaults later on
1650               will not change the A or P of previously created numbers (i.e., A and P of
1651               $x will be what was in effect when $x was created)
1652             * If given undef for A and P, NO rounding will occur, and the globals will
1653               NOT be used. This is used by subclasses to create numbers without
1654               suffering rounding in the parent. Thus a subclass is able to have its own
1655               globals enforced upon creation of a number by using
1656               $x = Math::BigInt->new($number,undef,undef):
1657
1658                   use Math::BigInt::SomeSubclass;
1659                   use Math::BigInt;
1660
1661                   Math::BigInt->accuracy(2);
1662                   Math::BigInt::SomeSubClass->accuracy(3);
1663                   $x = Math::BigInt::SomeSubClass->new(1234);
1664
1665               $x is now 1230, and not 1200. A subclass might choose to implement
1666               this otherwise, e.g. falling back to the parent's A and P.
1667
1668       Usage
1669             * If A or P are enabled/defined, they are used to round the result of each
1670               operation according to the rules below
1671             * Negative P is ignored in Math::BigInt, since Math::BigInt objects never
1672               have digits after the decimal point
1673             * Math::BigFloat uses Math::BigInt internally, but setting A or P inside
1674               Math::BigInt as globals does not tamper with the parts of a Math::BigFloat.
1675               A flag is used to mark all Math::BigFloat numbers as 'never round'.
1676
1677       Precedence
1678             * It only makes sense that a number has only one of A or P at a time.
1679               If you set either A or P on one object, or globally, the other one will
1680               be automatically cleared.
1681             * If two objects are involved in an operation, and one of them has A in
1682               effect, and the other P, this results in an error (NaN).
1683             * A takes precedence over P (Hint: A comes before P).
1684               If neither of them is defined, nothing is used, i.e. the result will have
1685               as many digits as it can (with an exception for bdiv/bsqrt) and will not
1686               be rounded.
1687             * There is another setting for bdiv() (and thus for bsqrt()). If neither of
1688               A or P is defined, bdiv() will use a fallback (F) of $div_scale digits.
1689               If either the dividend's or the divisor's mantissa has more digits than
1690               the value of F, the higher value will be used instead of F.
1691               This is to limit the digits (A) of the result (just consider what would
1692               happen with unlimited A and P in the case of 1/3 :-)
1693             * bdiv will calculate (at least) 4 more digits than required (determined by
1694               A, P or F), and, if F is not used, round the result
1695               (this will still fail in the case of a result like 0.12345000000001 with A
1696               or P of 5, but this can not be helped - or can it?)
1697             * Thus you can have the math done by on Math::Big* class in two modi:
1698               + never round (this is the default):
1699                 This is done by setting A and P to undef. No math operation
1700                 will round the result, with bdiv() and bsqrt() as exceptions to guard
1701                 against overflows. You must explicitly call bround(), bfround() or
1702                 round() (the latter with parameters).
1703                 Note: Once you have rounded a number, the settings will 'stick' on it
1704                 and 'infect' all other numbers engaged in math operations with it, since
1705                 local settings have the highest precedence. So, to get SaferRound[tm],
1706                 use a copy() before rounding like this:
1707
1708                   $x = Math::BigFloat->new(12.34);
1709                   $y = Math::BigFloat->new(98.76);
1710                   $z = $x * $y;                           # 1218.6984
1711                   print $x->copy()->bround(3);            # 12.3 (but A is now 3!)
1712                   $z = $x * $y;                           # still 1218.6984, without
1713                                                           # copy would have been 1210!
1714
1715               + round after each op:
1716                 After each single operation (except for testing like is_zero()), the
1717                 method round() is called and the result is rounded appropriately. By
1718                 setting proper values for A and P, you can have all-the-same-A or
1719                 all-the-same-P modes. For example, Math::Currency might set A to undef,
1720                 and P to -2, globally.
1721
1722            ?Maybe an extra option that forbids local A & P settings would be in order,
1723            ?so that intermediate rounding does not 'poison' further math?
1724
1725       Overriding globals
1726             * you will be able to give A, P and R as an argument to all the calculation
1727               routines; the second parameter is A, the third one is P, and the fourth is
1728               R (shift right by one for binary operations like badd). P is used only if
1729               the first parameter (A) is undefined. These three parameters override the
1730               globals in the order detailed as follows, i.e. the first defined value
1731               wins:
1732               (local: per object, global: global default, parameter: argument to sub)
1733                 + parameter A
1734                 + parameter P
1735                 + local A (if defined on both of the operands: smaller one is taken)
1736                 + local P (if defined on both of the operands: bigger one is taken)
1737                 + global A
1738                 + global P
1739                 + global F
1740             * bsqrt() will hand its arguments to bdiv(), as it used to, only now for two
1741               arguments (A and P) instead of one
1742
1743       Local settings
1744             * You can set A or P locally by using $x->accuracy() or
1745               $x->precision()
1746               and thus force different A and P for different objects/numbers.
1747             * Setting A or P this way immediately rounds $x to the new value.
1748             * $x->accuracy() clears $x->precision(), and vice versa.
1749
1750       Rounding
1751             * the rounding routines will use the respective global or local settings.
1752               bround() is for accuracy rounding, while bfround() is for precision
1753             * the two rounding functions take as the second parameter one of the
1754               following rounding modes (R):
1755               'even', 'odd', '+inf', '-inf', 'zero', 'trunc', 'common'
1756             * you can set/get the global R by using Math::SomeClass->round_mode()
1757               or by setting $Math::SomeClass::round_mode
1758             * after each operation, $result->round() is called, and the result may
1759               eventually be rounded (that is, if A or P were set either locally,
1760               globally or as parameter to the operation)
1761             * to manually round a number, call $x->round($A,$P,$round_mode);
1762               this will round the number by using the appropriate rounding function
1763               and then normalize it.
1764             * rounding modifies the local settings of the number:
1765
1766                   $x = Math::BigFloat->new(123.456);
1767                   $x->accuracy(5);
1768                   $x->bround(4);
1769
1770               Here 4 takes precedence over 5, so 123.5 is the result and $x->accuracy()
1771               will be 4 from now on.
1772
1773       Default values
1774             * R: 'even'
1775             * F: 40
1776             * A: undef
1777             * P: undef
1778
1779       Remarks
1780             * The defaults are set up so that the new code gives the same results as
1781               the old code (except in a few cases on bdiv):
1782               + Both A and P are undefined and thus will not be used for rounding
1783                 after each operation.
1784               + round() is thus a no-op, unless given extra parameters A and P
1785

Infinity and Not a Number

1787       While Math::BigInt has extensive handling of inf and NaN, certain
1788       quirks remain.
1789
1790       oct()/hex()
1791           These perl routines currently (as of Perl v.5.8.6) cannot handle
1792           passed inf.
1793
1794               te@linux:~> perl -wle 'print 2 ** 3333'
1795               Inf
1796               te@linux:~> perl -wle 'print 2 ** 3333 == 2 ** 3333'
1797               1
1798               te@linux:~> perl -wle 'print oct(2 ** 3333)'
1799               0
1800               te@linux:~> perl -wle 'print hex(2 ** 3333)'
1801               Illegal hexadecimal digit 'I' ignored at -e line 1.
1802               0
1803
1804           The same problems occur if you pass them Math::BigInt->binf()
1805           objects. Since overloading these routines is not possible, this
1806           cannot be fixed from Math::BigInt.
1807

INTERNALS

1809       You should neither care about nor depend on the internal
1810       representation; it might change without notice. Use ONLY method calls
1811       like "$x->sign();" instead relying on the internal representation.
1812
1813   MATH LIBRARY
1814       The mathematical computations are performed by a backend library. It is
1815       not required to specify which backend library to use, but some backend
1816       libraries are much faster than the default library.
1817
1818       The default library
1819
1820       The default library is Math::BigInt::Calc, which is implemented in pure
1821       Perl and hence does not require a compiler.
1822
1823       Specifying a library
1824
1825       The simple case
1826
1827           use Math::BigInt;
1828
1829       is equivalent to saying
1830
1831           use Math::BigInt try => 'Calc';
1832
1833       You can use a different backend library with, e.g.,
1834
1835           use Math::BigInt try => 'GMP';
1836
1837       which attempts to load the Math::BigInt::GMP library, and falls back to
1838       the default library if the specified library can't be loaded.
1839
1840       Multiple libraries can be specified by separating them by a comma,
1841       e.g.,
1842
1843           use Math::BigInt try => 'GMP,Pari';
1844
1845       If you request a specific set of libraries and do not allow fallback to
1846       the default library, specify them using "only",
1847
1848           use Math::BigInt only => 'GMP,Pari';
1849
1850       If you prefer a specific set of libraries, but want to see a warning if
1851       the fallback library is used, specify them using "lib",
1852
1853           use Math::BigInt lib => 'GMP,Pari';
1854
1855       The following first tries to find Math::BigInt::Foo, then
1856       Math::BigInt::Bar, and if this also fails, reverts to
1857       Math::BigInt::Calc:
1858
1859           use Math::BigInt try => 'Foo,Math::BigInt::Bar';
1860
1861       Which library to use?
1862
1863       Note: General purpose packages should not be explicit about the library
1864       to use; let the script author decide which is best.
1865
1866       Math::BigInt::GMP, Math::BigInt::Pari, and Math::BigInt::GMPz are in
1867       cases involving big numbers much faster than Math::BigInt::Calc.
1868       However these libraries are slower when dealing with very small numbers
1869       (less than about 20 digits) and when converting very large numbers to
1870       decimal (for instance for printing, rounding, calculating their length
1871       in decimal etc.).
1872
1873       So please select carefully what library you want to use.
1874
1875       Different low-level libraries use different formats to store the
1876       numbers, so mixing them won't work. You should not depend on the number
1877       having a specific internal format.
1878
1879       See the respective math library module documentation for further
1880       details.
1881
1882       Loading multiple libraries
1883
1884       The first library that is successfully loaded is the one that will be
1885       used. Any further attempts at loading a different module will be
1886       ignored. This is to avoid the situation where module A requires math
1887       library X, and module B requires math library Y, causing modules A and
1888       B to be incompatible. For example,
1889
1890           use Math::BigInt;                   # loads default "Calc"
1891           use Math::BigFloat only => "GMP";   # ignores "GMP"
1892
1893   SIGN
1894       The sign is either '+', '-', 'NaN', '+inf' or '-inf'.
1895
1896       A sign of 'NaN' is used to represent the result when input arguments
1897       are not numbers or as a result of 0/0. '+inf' and '-inf' represent plus
1898       respectively minus infinity. You get '+inf' when dividing a positive
1899       number by 0, and '-inf' when dividing any negative number by 0.
1900

EXAMPLES

1902         use Math::BigInt;
1903
1904         sub bigint { Math::BigInt->new(shift); }
1905
1906         $x = Math::BigInt->bstr("1234")       # string "1234"
1907         $x = "$x";                            # same as bstr()
1908         $x = Math::BigInt->bneg("1234");      # Math::BigInt "-1234"
1909         $x = Math::BigInt->babs("-12345");    # Math::BigInt "12345"
1910         $x = Math::BigInt->bnorm("-0.00");    # Math::BigInt "0"
1911         $x = bigint(1) + bigint(2);           # Math::BigInt "3"
1912         $x = bigint(1) + "2";                 # ditto (auto-Math::BigIntify of "2")
1913         $x = bigint(1);                       # Math::BigInt "1"
1914         $x = $x + 5 / 2;                      # Math::BigInt "3"
1915         $x = $x ** 3;                         # Math::BigInt "27"
1916         $x *= 2;                              # Math::BigInt "54"
1917         $x = Math::BigInt->new(0);            # Math::BigInt "0"
1918         $x--;                                 # Math::BigInt "-1"
1919         $x = Math::BigInt->badd(4,5)          # Math::BigInt "9"
1920         print $x->bsstr();                    # 9e+0
1921
1922       Examples for rounding:
1923
1924         use Math::BigFloat;
1925         use Test::More;
1926
1927         $x = Math::BigFloat->new(123.4567);
1928         $y = Math::BigFloat->new(123.456789);
1929         Math::BigFloat->accuracy(4);          # no more A than 4
1930
1931         is ($x->copy()->bround(),123.4);      # even rounding
1932         print $x->copy()->bround(),"\n";      # 123.4
1933         Math::BigFloat->round_mode('odd');    # round to odd
1934         print $x->copy()->bround(),"\n";      # 123.5
1935         Math::BigFloat->accuracy(5);          # no more A than 5
1936         Math::BigFloat->round_mode('odd');    # round to odd
1937         print $x->copy()->bround(),"\n";      # 123.46
1938         $y = $x->copy()->bround(4),"\n";      # A = 4: 123.4
1939         print "$y, ",$y->accuracy(),"\n";     # 123.4, 4
1940
1941         Math::BigFloat->accuracy(undef);      # A not important now
1942         Math::BigFloat->precision(2);         # P important
1943         print $x->copy()->bnorm(),"\n";       # 123.46
1944         print $x->copy()->bround(),"\n";      # 123.46
1945
1946       Examples for converting:
1947
1948         my $x = Math::BigInt->new('0b1'.'01' x 123);
1949         print "bin: ",$x->as_bin()," hex:",$x->as_hex()," dec: ",$x,"\n";
1950

Autocreating constants

1952       After "use Math::BigInt ':constant'" all the integer decimal,
1953       hexadecimal and binary constants in the given scope are converted to
1954       "Math::BigInt". This conversion happens at compile time.
1955
1956       In particular,
1957
1958         perl -MMath::BigInt=:constant -e 'print 2**100,"\n"'
1959
1960       prints the integer value of "2**100". Note that without conversion of
1961       constants the expression 2**100 is calculated using Perl scalars.
1962
1963       Please note that strings and floating point constants are not affected,
1964       so that
1965
1966           use Math::BigInt qw/:constant/;
1967
1968           $x = 1234567890123456789012345678901234567890
1969                   + 123456789123456789;
1970           $y = '1234567890123456789012345678901234567890'
1971                   + '123456789123456789';
1972
1973       does not give you what you expect. You need an explicit
1974       Math::BigInt->new() around one of the operands. You should also quote
1975       large constants to protect loss of precision:
1976
1977           use Math::BigInt;
1978
1979           $x = Math::BigInt->new('1234567889123456789123456789123456789');
1980
1981       Without the quotes Perl would convert the large number to a floating
1982       point constant at compile time and then hand the result to
1983       Math::BigInt, which results in an truncated result or a NaN.
1984
1985       This also applies to integers that look like floating point constants:
1986
1987           use Math::BigInt ':constant';
1988
1989           print ref(123e2),"\n";
1990           print ref(123.2e2),"\n";
1991
1992       prints nothing but newlines. Use either bignum or Math::BigFloat to get
1993       this to work.
1994

PERFORMANCE

1996       Using the form $x += $y; etc over $x = $x + $y is faster, since a copy
1997       of $x must be made in the second case. For long numbers, the copy can
1998       eat up to 20% of the work (in the case of addition/subtraction, less
1999       for multiplication/division). If $y is very small compared to $x, the
2000       form $x += $y is MUCH faster than $x = $x + $y since making the copy of
2001       $x takes more time then the actual addition.
2002
2003       With a technique called copy-on-write, the cost of copying with
2004       overload could be minimized or even completely avoided. A test
2005       implementation of COW did show performance gains for overloaded math,
2006       but introduced a performance loss due to a constant overhead for all
2007       other operations. So Math::BigInt does currently not COW.
2008
2009       The rewritten version of this module (vs. v0.01) is slower on certain
2010       operations, like "new()", "bstr()" and "numify()". The reason are that
2011       it does now more work and handles much more cases. The time spent in
2012       these operations is usually gained in the other math operations so that
2013       code on the average should get (much) faster. If they don't, please
2014       contact the author.
2015
2016       Some operations may be slower for small numbers, but are significantly
2017       faster for big numbers. Other operations are now constant (O(1), like
2018       "bneg()", "babs()" etc), instead of O(N) and thus nearly always take
2019       much less time.  These optimizations were done on purpose.
2020
2021       If you find the Calc module to slow, try to install any of the
2022       replacement modules and see if they help you.
2023
2024   Alternative math libraries
2025       You can use an alternative library to drive Math::BigInt. See the
2026       section "MATH LIBRARY" for more information.
2027
2028       For more benchmark results see
2029       <http://bloodgate.com/perl/benchmarks.html>.
2030

SUBCLASSING

2032   Subclassing Math::BigInt
2033       The basic design of Math::BigInt allows simple subclasses with very
2034       little work, as long as a few simple rules are followed:
2035
2036       •   The public API must remain consistent, i.e. if a sub-class is
2037           overloading addition, the sub-class must use the same name, in this
2038           case badd(). The reason for this is that Math::BigInt is optimized
2039           to call the object methods directly.
2040
2041       •   The private object hash keys like "$x->{sign}" may not be changed,
2042           but additional keys can be added, like "$x->{_custom}".
2043
2044       •   Accessor functions are available for all existing object hash keys
2045           and should be used instead of directly accessing the internal hash
2046           keys. The reason for this is that Math::BigInt itself has a
2047           pluggable interface which permits it to support different storage
2048           methods.
2049
2050       More complex sub-classes may have to replicate more of the logic
2051       internal of Math::BigInt if they need to change more basic behaviors. A
2052       subclass that needs to merely change the output only needs to overload
2053       "bstr()".
2054
2055       All other object methods and overloaded functions can be directly
2056       inherited from the parent class.
2057
2058       At the very minimum, any subclass needs to provide its own "new()" and
2059       can store additional hash keys in the object. There are also some
2060       package globals that must be defined, e.g.:
2061
2062           # Globals
2063           $accuracy = undef;
2064           $precision = -2;       # round to 2 decimal places
2065           $round_mode = 'even';
2066           $div_scale = 40;
2067
2068       Additionally, you might want to provide the following two globals to
2069       allow auto-upgrading and auto-downgrading to work correctly:
2070
2071           $upgrade = undef;
2072           $downgrade = undef;
2073
2074       This allows Math::BigInt to correctly retrieve package globals from the
2075       subclass, like $SubClass::precision. See t/Math/BigInt/Subclass.pm or
2076       t/Math/BigFloat/SubClass.pm completely functional subclass examples.
2077
2078       Don't forget to
2079
2080           use overload;
2081
2082       in your subclass to automatically inherit the overloading from the
2083       parent. If you like, you can change part of the overloading, look at
2084       Math::String for an example.
2085

UPGRADING

2087       When used like this:
2088
2089           use Math::BigInt upgrade => 'Foo::Bar';
2090
2091       certain operations 'upgrade' their calculation and thus the result to
2092       the class Foo::Bar. Usually this is used in conjunction with
2093       Math::BigFloat:
2094
2095           use Math::BigInt upgrade => 'Math::BigFloat';
2096
2097       As a shortcut, you can use the module bignum:
2098
2099           use bignum;
2100
2101       Also good for one-liners:
2102
2103           perl -Mbignum -le 'print 2 ** 255'
2104
2105       This makes it possible to mix arguments of different classes (as in 2.5
2106       + 2) as well es preserve accuracy (as in sqrt(3)).
2107
2108       Beware: This feature is not fully implemented yet.
2109
2110   Auto-upgrade
2111       The following methods upgrade themselves unconditionally; that is if
2112       upgrade is in effect, they always hands up their work:
2113
2114           div bsqrt blog bexp bpi bsin bcos batan batan2
2115
2116       All other methods upgrade themselves only when one (or all) of their
2117       arguments are of the class mentioned in $upgrade.
2118

EXPORTS

2120       "Math::BigInt" exports nothing by default, but can export the following
2121       methods:
2122
2123           bgcd
2124           blcm
2125

CAVEATS

2127       Some things might not work as you expect them. Below is documented what
2128       is known to be troublesome:
2129
2130       Comparing numbers as strings
2131           Both "bstr()" and "bsstr()" as well as stringify via overload drop
2132           the leading '+'. This is to be consistent with Perl and to make
2133           "cmp" (especially with overloading) to work as you expect. It also
2134           solves problems with "Test.pm" and Test::More, which stringify
2135           arguments before comparing them.
2136
2137           Mark Biggar said, when asked about to drop the '+' altogether, or
2138           make only "cmp" work:
2139
2140               I agree (with the first alternative), don't add the '+' on positive
2141               numbers.  It's not as important anymore with the new internal form
2142               for numbers.  It made doing things like abs and neg easier, but
2143               those have to be done differently now anyway.
2144
2145           So, the following examples now works as expected:
2146
2147               use Test::More tests => 1;
2148               use Math::BigInt;
2149
2150               my $x = Math::BigInt -> new(3*3);
2151               my $y = Math::BigInt -> new(3*3);
2152
2153               is($x,3*3, 'multiplication');
2154               print "$x eq 9" if $x eq $y;
2155               print "$x eq 9" if $x eq '9';
2156               print "$x eq 9" if $x eq 3*3;
2157
2158           Additionally, the following still works:
2159
2160               print "$x == 9" if $x == $y;
2161               print "$x == 9" if $x == 9;
2162               print "$x == 9" if $x == 3*3;
2163
2164           There is now a "bsstr()" method to get the string in scientific
2165           notation aka 1e+2 instead of 100. Be advised that overloaded 'eq'
2166           always uses bstr() for comparison, but Perl represents some numbers
2167           as 100 and others as 1e+308.  If in doubt, convert both arguments
2168           to Math::BigInt before comparing them as strings:
2169
2170               use Test::More tests => 3;
2171               use Math::BigInt;
2172
2173               $x = Math::BigInt->new('1e56'); $y = 1e56;
2174               is($x,$y);                     # fails
2175               is($x->bsstr(),$y);            # okay
2176               $y = Math::BigInt->new($y);
2177               is($x,$y);                     # okay
2178
2179           Alternatively, simply use "<=>" for comparisons, this always gets
2180           it right. There is not yet a way to get a number automatically
2181           represented as a string that matches exactly the way Perl
2182           represents it.
2183
2184           See also the section about "Infinity and Not a Number" for problems
2185           in comparing NaNs.
2186
2187       int()
2188           "int()" returns (at least for Perl v5.7.1 and up) another
2189           Math::BigInt, not a Perl scalar:
2190
2191               $x = Math::BigInt->new(123);
2192               $y = int($x);                           # 123 as a Math::BigInt
2193               $x = Math::BigFloat->new(123.45);
2194               $y = int($x);                           # 123 as a Math::BigFloat
2195
2196           If you want a real Perl scalar, use "numify()":
2197
2198               $y = $x->numify();                      # 123 as a scalar
2199
2200           This is seldom necessary, though, because this is done
2201           automatically, like when you access an array:
2202
2203               $z = $array[$x];                        # does work automatically
2204
2205       Modifying and =
2206           Beware of:
2207
2208               $x = Math::BigFloat->new(5);
2209               $y = $x;
2210
2211           This makes a second reference to the same object and stores it in
2212           $y. Thus anything that modifies $x (except overloaded operators)
2213           also modifies $y, and vice versa. Or in other words, "=" is only
2214           safe if you modify your Math::BigInt objects only via overloaded
2215           math. As soon as you use a method call it breaks:
2216
2217               $x->bmul(2);
2218               print "$x, $y\n";       # prints '10, 10'
2219
2220           If you want a true copy of $x, use:
2221
2222               $y = $x->copy();
2223
2224           You can also chain the calls like this, this first makes a copy and
2225           then multiply it by 2:
2226
2227               $y = $x->copy()->bmul(2);
2228
2229           See also the documentation for overload.pm regarding "=".
2230
2231       Overloading -$x
2232           The following:
2233
2234               $x = -$x;
2235
2236           is slower than
2237
2238               $x->bneg();
2239
2240           since overload calls "sub($x,0,1);" instead of "neg($x)". The first
2241           variant needs to preserve $x since it does not know that it later
2242           gets overwritten.  This makes a copy of $x and takes O(N), but
2243           $x->bneg() is O(1).
2244
2245       Mixing different object types
2246           With overloaded operators, it is the first (dominating) operand
2247           that determines which method is called. Here are some examples
2248           showing what actually gets called in various cases.
2249
2250               use Math::BigInt;
2251               use Math::BigFloat;
2252
2253               $mbf  = Math::BigFloat->new(5);
2254               $mbi2 = Math::BigInt->new(5);
2255               $mbi  = Math::BigInt->new(2);
2256                                               # what actually gets called:
2257               $float = $mbf + $mbi;           # $mbf->badd($mbi)
2258               $float = $mbf / $mbi;           # $mbf->bdiv($mbi)
2259               $integer = $mbi + $mbf;         # $mbi->badd($mbf)
2260               $integer = $mbi2 / $mbi;        # $mbi2->bdiv($mbi)
2261               $integer = $mbi2 / $mbf;        # $mbi2->bdiv($mbf)
2262
2263           For instance, Math::BigInt->bdiv() always returns a Math::BigInt,
2264           regardless of whether the second operant is a Math::BigFloat. To
2265           get a Math::BigFloat you either need to call the operation
2266           manually, make sure each operand already is a Math::BigFloat, or
2267           cast to that type via Math::BigFloat->new():
2268
2269               $float = Math::BigFloat->new($mbi2) / $mbi;     # = 2.5
2270
2271           Beware of casting the entire expression, as this would cast the
2272           result, at which point it is too late:
2273
2274               $float = Math::BigFloat->new($mbi2 / $mbi);     # = 2
2275
2276           Beware also of the order of more complicated expressions like:
2277
2278               $integer = ($mbi2 + $mbi) / $mbf;               # int / float => int
2279               $integer = $mbi2 / Math::BigFloat->new($mbi);   # ditto
2280
2281           If in doubt, break the expression into simpler terms, or cast all
2282           operands to the desired resulting type.
2283
2284           Scalar values are a bit different, since:
2285
2286               $float = 2 + $mbf;
2287               $float = $mbf + 2;
2288
2289           both result in the proper type due to the way the overloaded math
2290           works.
2291
2292           This section also applies to other overloaded math packages, like
2293           Math::String.
2294
2295           One solution to you problem might be autoupgrading|upgrading. See
2296           the pragmas bignum, bigint and bigrat for an easy way to do this.
2297

BUGS

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

SUPPORT

2306       You can find documentation for this module with the perldoc command.
2307
2308           perldoc Math::BigInt
2309
2310       You can also look for information at:
2311
2312       •   GitHub
2313
2314           <https://github.com/pjacklam/p5-Math-BigInt>
2315
2316       •   RT: CPAN's request tracker
2317
2318           <https://rt.cpan.org/Dist/Display.html?Name=Math-BigInt>
2319
2320       •   MetaCPAN
2321
2322           <https://metacpan.org/release/Math-BigInt>
2323
2324       •   CPAN Testers Matrix
2325
2326           <http://matrix.cpantesters.org/?dist=Math-BigInt>
2327
2328       •   CPAN Ratings
2329
2330           <https://cpanratings.perl.org/dist/Math-BigInt>
2331
2332       •   The Bignum mailing list
2333
2334           •   Post to mailing list
2335
2336               "bignum at lists.scsys.co.uk"
2337
2338           •   View mailing list
2339
2340               <http://lists.scsys.co.uk/pipermail/bignum/>
2341
2342           •   Subscribe/Unsubscribe
2343
2344               <http://lists.scsys.co.uk/cgi-bin/mailman/listinfo/bignum>
2345

LICENSE

2347       This program is free software; you may redistribute it and/or modify it
2348       under the same terms as Perl itself.
2349

SEE ALSO

2351       Math::BigFloat and Math::BigRat as well as the backends
2352       Math::BigInt::FastCalc, Math::BigInt::GMP, and Math::BigInt::Pari.
2353
2354       The pragmas bignum, bigint and bigrat also might be of interest because
2355       they solve the autoupgrading/downgrading issue, at least partly.
2356

AUTHORS

2358       •   Mark Biggar, overloaded interface by Ilya Zakharevich, 1996-2001.
2359
2360       •   Completely rewritten by Tels <http://bloodgate.com>, 2001-2008.
2361
2362       •   Florian Ragwitz <flora@cpan.org>, 2010.
2363
2364       •   Peter John Acklam <pjacklam@gmail.com>, 2011-.
2365
2366       Many people contributed in one or more ways to the final beast, see the
2367       file CREDITS for an (incomplete) list. If you miss your name, please
2368       drop me a mail. Thank you!
2369
2370
2371
2372perl v5.34.0                      2021-09-22                   Math::BigInt(3)
Impressum