1Math::BigInt(3) User Contributed Perl Documentation Math::BigInt(3)
2
3
4
6 Math::BigInt - arbitrary size integer math package
7
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 $x->fparts(); # numerator and denominator
178 $x->numerator(); # numerator
179 $x->denominator(); # denominator
180
181 # Conversion methods (do not modify the invocand)
182
183 $x->bstr(); # decimal notation, possibly zero padded
184 $x->bsstr(); # string in scientific notation with integers
185 $x->bnstr(); # string in normalized notation
186 $x->bestr(); # string in engineering notation
187 $x->bdstr(); # string in decimal notation
188
189 $x->to_hex(); # as signed hexadecimal string
190 $x->to_bin(); # as signed binary string
191 $x->to_oct(); # as signed octal string
192 $x->to_bytes(); # as byte string
193 $x->to_base($b); # as string in any base
194 $x->to_base_num($b); # as array of integers in any base
195
196 $x->as_hex(); # as signed hexadecimal string with prefixed 0x
197 $x->as_bin(); # as signed binary string with prefixed 0b
198 $x->as_oct(); # as signed octal string with prefixed 0
199
200 # Other conversion methods
201
202 $x->numify(); # return as scalar (might overflow or underflow)
203
205 Math::BigInt provides support for arbitrary precision integers.
206 Overloading is also provided for Perl operators.
207
208 Input
209 Input values to these routines may be any scalar number or string that
210 looks like a number and represents an integer. Anything that is
211 accepted by Perl as a literal numeric constant should be accepted by
212 this module, except that finite non-integers return NaN.
213
214 • Leading and trailing whitespace is ignored.
215
216 • Leading zeros are ignored, except for floating point numbers with a
217 binary exponent, in which case the number is interpreted as an
218 octal floating point number. For example, "01.4p+0" gives 1.5,
219 "00.4p+0" gives 0.5, but "0.4p+0" gives a NaN. And while "0377"
220 gives 255, "0377p0" gives 255.
221
222 • If the string has a "0x" or "0X" prefix, it is interpreted as a
223 hexadecimal number.
224
225 • If the string has a "0o" or "0O" prefix, it is interpreted as an
226 octal number. A floating point literal with a "0" prefix is also
227 interpreted as an octal number.
228
229 • If the string has a "0b" or "0B" prefix, it is interpreted as a
230 binary number.
231
232 • Underline characters are allowed in the same way as they are
233 allowed in literal numerical constants.
234
235 • If the string can not be interpreted, or does not represent a
236 finite integer, NaN is returned.
237
238 • For hexadecimal, octal, and binary floating point numbers, the
239 exponent must be separated from the significand (mantissa) by the
240 letter "p" or "P", not "e" or "E" as with decimal numbers.
241
242 Some examples of valid string input
243
244 Input string Resulting value
245
246 123 123
247 1.23e2 123
248 12300e-2 123
249
250 67_538_754 67538754
251 -4_5_6.7_8_9e+0_1_0 -4567890000000
252
253 0x13a 314
254 0x13ap0 314
255 0x1.3ap+8 314
256 0x0.00013ap+24 314
257 0x13a000p-12 314
258
259 0o472 314
260 0o1.164p+8 314
261 0o0.0001164p+20 314
262 0o1164000p-10 314
263
264 0472 472 Note!
265 01.164p+8 314
266 00.0001164p+20 314
267 01164000p-10 314
268
269 0b100111010 314
270 0b1.0011101p+8 314
271 0b0.00010011101p+12 314
272 0b100111010000p-3 314
273
274 Input given as scalar numbers might lose precision. Quote your input to
275 ensure that no digits are lost:
276
277 $x = Math::BigInt->new( 56789012345678901234 ); # bad
278 $x = Math::BigInt->new('56789012345678901234'); # good
279
280 Currently, "Math::BigInt-"new()> (no input argument) and
281 "Math::BigInt-"new("")> return 0. This might change in the future, so
282 always use the following explicit forms to get a zero:
283
284 $zero = Math::BigInt->bzero();
285
286 Output
287 Output values are usually Math::BigInt objects.
288
289 Boolean operators "is_zero()", "is_one()", "is_inf()", etc. return true
290 or false.
291
292 Comparison operators "bcmp()" and "bacmp()") return -1, 0, 1, or undef.
293
295 Configuration methods
296 Each of the methods below (except config(), accuracy() and precision())
297 accepts three additional parameters. These arguments $A, $P and $R are
298 "accuracy", "precision" and "round_mode". Please see the section about
299 "ACCURACY and PRECISION" for more information.
300
301 Setting a class variable effects all object instance that are created
302 afterwards.
303
304 accuracy()
305 Math::BigInt->accuracy(5); # set class accuracy
306 $x->accuracy(5); # set instance accuracy
307
308 $A = Math::BigInt->accuracy(); # get class accuracy
309 $A = $x->accuracy(); # get instance accuracy
310
311 Set or get the accuracy, i.e., the number of significant digits.
312 The accuracy must be an integer. If the accuracy is set to "undef",
313 no rounding is done.
314
315 Alternatively, one can round the results explicitly using one of
316 "round()", "bround()" or "bfround()" or by passing the desired
317 accuracy to the method as an additional parameter:
318
319 my $x = Math::BigInt->new(30000);
320 my $y = Math::BigInt->new(7);
321 print scalar $x->copy()->bdiv($y, 2); # prints 4300
322 print scalar $x->copy()->bdiv($y)->bround(2); # prints 4300
323
324 Please see the section about "ACCURACY and PRECISION" for further
325 details.
326
327 $y = Math::BigInt->new(1234567); # $y is not rounded
328 Math::BigInt->accuracy(4); # set class accuracy to 4
329 $x = Math::BigInt->new(1234567); # $x is rounded automatically
330 print "$x $y"; # prints "1235000 1234567"
331
332 print $x->accuracy(); # prints "4"
333 print $y->accuracy(); # also prints "4", since
334 # class accuracy is 4
335
336 Math::BigInt->accuracy(5); # set class accuracy to 5
337 print $x->accuracy(); # prints "4", since instance
338 # accuracy is 4
339 print $y->accuracy(); # prints "5", since no instance
340 # accuracy, and class accuracy is 5
341
342 Note: Each class has it's own globals separated from Math::BigInt,
343 but it is possible to subclass Math::BigInt and make the globals of
344 the subclass aliases to the ones from Math::BigInt.
345
346 precision()
347 Math::BigInt->precision(-2); # set class precision
348 $x->precision(-2); # set instance precision
349
350 $P = Math::BigInt->precision(); # get class precision
351 $P = $x->precision(); # get instance precision
352
353 Set or get the precision, i.e., the place to round relative to the
354 decimal point. The precision must be a integer. Setting the
355 precision to $P means that each number is rounded up or down,
356 depending on the rounding mode, to the nearest multiple of 10**$P.
357 If the precision is set to "undef", no rounding is done.
358
359 You might want to use "accuracy()" instead. With "accuracy()" you
360 set the number of digits each result should have, with
361 "precision()" you set the place where to round.
362
363 Please see the section about "ACCURACY and PRECISION" for further
364 details.
365
366 $y = Math::BigInt->new(1234567); # $y is not rounded
367 Math::BigInt->precision(4); # set class precision to 4
368 $x = Math::BigInt->new(1234567); # $x is rounded automatically
369 print $x; # prints "1230000"
370
371 Note: Each class has its own globals separated from Math::BigInt,
372 but it is possible to subclass Math::BigInt and make the globals of
373 the subclass aliases to the ones from Math::BigInt.
374
375 div_scale()
376 Set/get the fallback accuracy. This is the accuracy used when
377 neither accuracy nor precision is set explicitly. It is used when a
378 computation might otherwise attempt to return an infinite number of
379 digits.
380
381 round_mode()
382 Set/get the rounding mode.
383
384 upgrade()
385 Set/get the class for upgrading. When a computation might result in
386 a non-integer, the operands are upgraded to this class. This is
387 used for instance by bignum. The default is "undef", i.e., no
388 upgrading.
389
390 # with no upgrading
391 $x = Math::BigInt->new(12);
392 $y = Math::BigInt->new(5);
393 print $x / $y, "\n"; # 2 as a Math::BigInt
394
395 # with upgrading to Math::BigFloat
396 Math::BigInt -> upgrade("Math::BigFloat");
397 print $x / $y, "\n"; # 2.4 as a Math::BigFloat
398
399 # with upgrading to Math::BigRat (after loading Math::BigRat)
400 Math::BigInt -> upgrade("Math::BigRat");
401 print $x / $y, "\n"; # 12/5 as a Math::BigRat
402
403 downgrade()
404 Set/get the class for downgrading. The default is "undef", i.e., no
405 downgrading. Downgrading is not done by Math::BigInt.
406
407 modify()
408 $x->modify('bpowd');
409
410 This method returns 0 if the object can be modified with the given
411 operation, or 1 if not.
412
413 This is used for instance by Math::BigInt::Constant.
414
415 config()
416 Math::BigInt->config("trap_nan" => 1); # set
417 $accu = Math::BigInt->config("accuracy"); # get
418
419 Set or get class variables. Read-only parameters are marked as RO.
420 Read-write parameters are marked as RW. The following parameters
421 are supported.
422
423 Parameter RO/RW Description
424 Example
425 ============================================================
426 lib RO Name of the math backend library
427 Math::BigInt::Calc
428 lib_version RO Version of the math backend library
429 0.30
430 class RO The class of config you just called
431 Math::BigRat
432 version RO version number of the class you used
433 0.10
434 upgrade RW To which class numbers are upgraded
435 undef
436 downgrade RW To which class numbers are downgraded
437 undef
438 precision RW Global precision
439 undef
440 accuracy RW Global accuracy
441 undef
442 round_mode RW Global round mode
443 even
444 div_scale RW Fallback accuracy for division etc.
445 40
446 trap_nan RW Trap NaNs
447 undef
448 trap_inf RW Trap +inf/-inf
449 undef
450
451 Constructor methods
452 new()
453 $x = Math::BigInt->new($str,$A,$P,$R);
454
455 Creates a new Math::BigInt object from a scalar or another
456 Math::BigInt object. The input is accepted as decimal, hexadecimal
457 (with leading '0x'), octal (with leading ('0o') or binary (with
458 leading '0b').
459
460 See "Input" for more info on accepted input formats.
461
462 from_dec()
463 $x = Math::BigInt->from_dec("314159"); # input is decimal
464
465 Interpret input as a decimal. It is equivalent to new(), but does
466 not accept anything but strings representing finite, decimal
467 numbers.
468
469 from_hex()
470 $x = Math::BigInt->from_hex("0xcafe"); # input is hexadecimal
471
472 Interpret input as a hexadecimal string. A "0x" or "x" prefix is
473 optional. A single underscore character may be placed right after
474 the prefix, if present, or between any two digits. If the input is
475 invalid, a NaN is returned.
476
477 from_oct()
478 $x = Math::BigInt->from_oct("0775"); # input is octal
479
480 Interpret the input as an octal string and return the corresponding
481 value. A "0" (zero) prefix is optional. A single underscore
482 character may be placed right after the prefix, if present, or
483 between any two digits. If the input is invalid, a NaN is returned.
484
485 from_bin()
486 $x = Math::BigInt->from_bin("0b10011"); # input is binary
487
488 Interpret the input as a binary string. A "0b" or "b" prefix is
489 optional. A single underscore character may be placed right after
490 the prefix, if present, or between any two digits. If the input is
491 invalid, a NaN is returned.
492
493 from_bytes()
494 $x = Math::BigInt->from_bytes("\xf3\x6b"); # $x = 62315
495
496 Interpret the input as a byte string, assuming big endian byte
497 order. The output is always a non-negative, finite integer.
498
499 In some special cases, from_bytes() matches the conversion done by
500 unpack():
501
502 $b = "\x4e"; # one char byte string
503 $x = Math::BigInt->from_bytes($b); # = 78
504 $y = unpack "C", $b; # ditto, but scalar
505
506 $b = "\xf3\x6b"; # two char byte string
507 $x = Math::BigInt->from_bytes($b); # = 62315
508 $y = unpack "S>", $b; # ditto, but scalar
509
510 $b = "\x2d\xe0\x49\xad"; # four char byte string
511 $x = Math::BigInt->from_bytes($b); # = 769673645
512 $y = unpack "L>", $b; # ditto, but scalar
513
514 $b = "\x2d\xe0\x49\xad\x2d\xe0\x49\xad"; # eight char byte string
515 $x = Math::BigInt->from_bytes($b); # = 3305723134637787565
516 $y = unpack "Q>", $b; # ditto, but scalar
517
518 from_base()
519 Given a string, a base, and an optional collation sequence,
520 interpret the string as a number in the given base. The collation
521 sequence describes the value of each character in the string.
522
523 If a collation sequence is not given, a default collation sequence
524 is used. If the base is less than or equal to 36, the collation
525 sequence is the string consisting of the 36 characters "0" to "9"
526 and "A" to "Z". In this case, the letter case in the input is
527 ignored. If the base is greater than 36, and smaller than or equal
528 to 62, the collation sequence is the string consisting of the 62
529 characters "0" to "9", "A" to "Z", and "a" to "z". A base larger
530 than 62 requires the collation sequence to be specified explicitly.
531
532 These examples show standard binary, octal, and hexadecimal
533 conversion. All cases return 250.
534
535 $x = Math::BigInt->from_base("11111010", 2);
536 $x = Math::BigInt->from_base("372", 8);
537 $x = Math::BigInt->from_base("fa", 16);
538
539 When the base is less than or equal to 36, and no collation
540 sequence is given, the letter case is ignored, so both of these
541 also return 250:
542
543 $x = Math::BigInt->from_base("6Y", 16);
544 $x = Math::BigInt->from_base("6y", 16);
545
546 When the base greater than 36, and no collation sequence is given,
547 the default collation sequence contains both uppercase and
548 lowercase letters, so the letter case in the input is not ignored:
549
550 $x = Math::BigInt->from_base("6S", 37); # $x is 250
551 $x = Math::BigInt->from_base("6s", 37); # $x is 276
552 $x = Math::BigInt->from_base("121", 3); # $x is 16
553 $x = Math::BigInt->from_base("XYZ", 36); # $x is 44027
554 $x = Math::BigInt->from_base("Why", 42); # $x is 58314
555
556 The collation sequence can be any set of unique characters. These
557 two cases are equivalent
558
559 $x = Math::BigInt->from_base("100", 2, "01"); # $x is 4
560 $x = Math::BigInt->from_base("|--", 2, "-|"); # $x is 4
561
562 from_base_num()
563 Returns a new Math::BigInt object given an array of values and a
564 base. This method is equivalent to "from_base()", but works on
565 numbers in an array rather than characters in a string. Unlike
566 "from_base()", all input values may be arbitrarily large.
567
568 $x = Math::BigInt->from_base_num([1, 1, 0, 1], 2) # $x is 13
569 $x = Math::BigInt->from_base_num([3, 125, 39], 128) # $x is 65191
570
571 bzero()
572 $x = Math::BigInt->bzero();
573 $x->bzero();
574
575 Returns a new Math::BigInt object representing zero. If used as an
576 instance method, assigns the value to the invocand.
577
578 bone()
579 $x = Math::BigInt->bone(); # +1
580 $x = Math::BigInt->bone("+"); # +1
581 $x = Math::BigInt->bone("-"); # -1
582 $x->bone(); # +1
583 $x->bone("+"); # +1
584 $x->bone('-'); # -1
585
586 Creates a new Math::BigInt object representing one. The optional
587 argument is either '-' or '+', indicating whether you want plus one
588 or minus one. If used as an instance method, assigns the value to
589 the invocand.
590
591 binf()
592 $x = Math::BigInt->binf($sign);
593
594 Creates a new Math::BigInt object representing infinity. The
595 optional argument is either '-' or '+', indicating whether you want
596 infinity or minus infinity. If used as an instance method, assigns
597 the value to the invocand.
598
599 $x->binf();
600 $x->binf('-');
601
602 bnan()
603 $x = Math::BigInt->bnan();
604
605 Creates a new Math::BigInt object representing NaN (Not A Number).
606 If used as an instance method, assigns the value to the invocand.
607
608 $x->bnan();
609
610 bpi()
611 $x = Math::BigInt->bpi(100); # 3
612 $x->bpi(100); # 3
613
614 Creates a new Math::BigInt object representing PI. If used as an
615 instance method, assigns the value to the invocand. With
616 Math::BigInt this always returns 3.
617
618 If upgrading is in effect, returns PI, rounded to N digits with the
619 current rounding mode:
620
621 use Math::BigFloat;
622 use Math::BigInt upgrade => "Math::BigFloat";
623 print Math::BigInt->bpi(3), "\n"; # 3.14
624 print Math::BigInt->bpi(100), "\n"; # 3.1415....
625
626 copy()
627 $x->copy(); # make a true copy of $x (unlike $y = $x)
628
629 as_int()
630 as_number()
631 These methods are called when Math::BigInt encounters an object it
632 doesn't know how to handle. For instance, assume $x is a
633 Math::BigInt, or subclass thereof, and $y is defined, but not a
634 Math::BigInt, or subclass thereof. If you do
635
636 $x -> badd($y);
637
638 $y needs to be converted into an object that $x can deal with. This
639 is done by first checking if $y is something that $x might be
640 upgraded to. If that is the case, no further attempts are made. The
641 next is to see if $y supports the method "as_int()". If it does,
642 "as_int()" is called, but if it doesn't, the next thing is to see
643 if $y supports the method "as_number()". If it does, "as_number()"
644 is called. The method "as_int()" (and "as_number()") is expected to
645 return either an object that has the same class as $x, a subclass
646 thereof, or a string that "ref($x)->new()" can parse to create an
647 object.
648
649 "as_number()" is an alias to "as_int()". "as_number" was introduced
650 in v1.22, while "as_int()" was introduced in v1.68.
651
652 In Math::BigInt, "as_int()" has the same effect as "copy()".
653
654 Boolean methods
655 None of these methods modify the invocand object.
656
657 is_zero()
658 $x->is_zero(); # true if $x is 0
659
660 Returns true if the invocand is zero and false otherwise.
661
662 is_one( [ SIGN ])
663 $x->is_one(); # true if $x is +1
664 $x->is_one("+"); # ditto
665 $x->is_one("-"); # true if $x is -1
666
667 Returns true if the invocand is one and false otherwise.
668
669 is_finite()
670 $x->is_finite(); # true if $x is not +inf, -inf or NaN
671
672 Returns true if the invocand is a finite number, i.e., it is
673 neither +inf, -inf, nor NaN.
674
675 is_inf( [ SIGN ] )
676 $x->is_inf(); # true if $x is +inf
677 $x->is_inf("+"); # ditto
678 $x->is_inf("-"); # true if $x is -inf
679
680 Returns true if the invocand is infinite and false otherwise.
681
682 is_nan()
683 $x->is_nan(); # true if $x is NaN
684
685 is_positive()
686 is_pos()
687 $x->is_positive(); # true if > 0
688 $x->is_pos(); # ditto
689
690 Returns true if the invocand is positive and false otherwise. A
691 "NaN" is neither positive nor negative.
692
693 is_negative()
694 is_neg()
695 $x->is_negative(); # true if < 0
696 $x->is_neg(); # ditto
697
698 Returns true if the invocand is negative and false otherwise. A
699 "NaN" is neither positive nor negative.
700
701 is_non_positive()
702 $x->is_non_positive(); # true if <= 0
703
704 Returns true if the invocand is negative or zero.
705
706 is_non_negative()
707 $x->is_non_negative(); # true if >= 0
708
709 Returns true if the invocand is positive or zero.
710
711 is_odd()
712 $x->is_odd(); # true if odd, false for even
713
714 Returns true if the invocand is odd and false otherwise. "NaN",
715 "+inf", and "-inf" are neither odd nor even.
716
717 is_even()
718 $x->is_even(); # true if $x is even
719
720 Returns true if the invocand is even and false otherwise. "NaN",
721 "+inf", "-inf" are not integers and are neither odd nor even.
722
723 is_int()
724 $x->is_int(); # true if $x is an integer
725
726 Returns true if the invocand is an integer and false otherwise.
727 "NaN", "+inf", "-inf" are not integers.
728
729 Comparison methods
730 None of these methods modify the invocand object. Note that a "NaN" is
731 neither less than, greater than, or equal to anything else, even a
732 "NaN".
733
734 bcmp()
735 $x->bcmp($y);
736
737 Returns -1, 0, 1 depending on whether $x is less than, equal to, or
738 grater than $y. Returns undef if any operand is a NaN.
739
740 bacmp()
741 $x->bacmp($y);
742
743 Returns -1, 0, 1 depending on whether the absolute value of $x is
744 less than, equal to, or grater than the absolute value of $y.
745 Returns undef if any operand is a NaN.
746
747 beq()
748 $x -> beq($y);
749
750 Returns true if and only if $x is equal to $y, and false otherwise.
751
752 bne()
753 $x -> bne($y);
754
755 Returns true if and only if $x is not equal to $y, and false
756 otherwise.
757
758 blt()
759 $x -> blt($y);
760
761 Returns true if and only if $x is equal to $y, and false otherwise.
762
763 ble()
764 $x -> ble($y);
765
766 Returns true if and only if $x is less than or equal to $y, and
767 false otherwise.
768
769 bgt()
770 $x -> bgt($y);
771
772 Returns true if and only if $x is greater than $y, and false
773 otherwise.
774
775 bge()
776 $x -> bge($y);
777
778 Returns true if and only if $x is greater than or equal to $y, and
779 false otherwise.
780
781 Arithmetic methods
782 These methods modify the invocand object and returns it.
783
784 bneg()
785 $x->bneg();
786
787 Negate the number, e.g. change the sign between '+' and '-', or
788 between '+inf' and '-inf', respectively. Does nothing for NaN or
789 zero.
790
791 babs()
792 $x->babs();
793
794 Set the number to its absolute value, e.g. change the sign from '-'
795 to '+' and from '-inf' to '+inf', respectively. Does nothing for
796 NaN or positive numbers.
797
798 bsgn()
799 $x->bsgn();
800
801 Signum function. Set the number to -1, 0, or 1, depending on
802 whether the number is negative, zero, or positive, respectively.
803 Does not modify NaNs.
804
805 bnorm()
806 $x->bnorm(); # normalize (no-op)
807
808 Normalize the number. This is a no-op and is provided only for
809 backwards compatibility.
810
811 binc()
812 $x->binc(); # increment x by 1
813
814 bdec()
815 $x->bdec(); # decrement x by 1
816
817 badd()
818 $x->badd($y); # addition (add $y to $x)
819
820 bsub()
821 $x->bsub($y); # subtraction (subtract $y from $x)
822
823 bmul()
824 $x->bmul($y); # multiplication (multiply $x by $y)
825
826 bmuladd()
827 $x->bmuladd($y,$z);
828
829 Multiply $x by $y, and then add $z to the result,
830
831 This method was added in v1.87 of Math::BigInt (June 2007).
832
833 bdiv()
834 $x->bdiv($y); # divide, set $x to quotient
835
836 Divides $x by $y by doing floored division (F-division), where the
837 quotient is the floored (rounded towards negative infinity)
838 quotient of the two operands. In list context, returns the
839 quotient and the remainder. The remainder is either zero or has the
840 same sign as the second operand. In scalar context, only the
841 quotient is returned.
842
843 The quotient is always the greatest integer less than or equal to
844 the real-valued quotient of the two operands, and the remainder
845 (when it is non-zero) always has the same sign as the second
846 operand; so, for example,
847
848 1 / 4 => ( 0, 1)
849 1 / -4 => (-1, -3)
850 -3 / 4 => (-1, 1)
851 -3 / -4 => ( 0, -3)
852 -11 / 2 => (-5, 1)
853 11 / -2 => (-5, -1)
854
855 The behavior of the overloaded operator % agrees with the behavior
856 of Perl's built-in % operator (as documented in the perlop
857 manpage), and the equation
858
859 $x == ($x / $y) * $y + ($x % $y)
860
861 holds true for any finite $x and finite, non-zero $y.
862
863 Perl's "use integer" might change the behaviour of % and / for
864 scalars. This is because under 'use integer' Perl does what the
865 underlying C library thinks is right, and this varies. However,
866 "use integer" does not change the way things are done with
867 Math::BigInt objects.
868
869 btdiv()
870 $x->btdiv($y); # divide, set $x to quotient
871
872 Divides $x by $y by doing truncated division (T-division), where
873 quotient is the truncated (rouneded towards zero) quotient of the
874 two operands. In list context, returns the quotient and the
875 remainder. The remainder is either zero or has the same sign as the
876 first operand. In scalar context, only the quotient is returned.
877
878 bmod()
879 $x->bmod($y); # modulus (x % y)
880
881 Returns $x modulo $y, i.e., the remainder after floored division
882 (F-division). This method is like Perl's % operator. See "bdiv()".
883
884 btmod()
885 $x->btmod($y); # modulus
886
887 Returns the remainer after truncated division (T-division). See
888 "btdiv()".
889
890 bmodinv()
891 $x->bmodinv($mod); # modular multiplicative inverse
892
893 Returns the multiplicative inverse of $x modulo $mod. If
894
895 $y = $x -> copy() -> bmodinv($mod)
896
897 then $y is the number closest to zero, and with the same sign as
898 $mod, satisfying
899
900 ($x * $y) % $mod = 1 % $mod
901
902 If $x and $y are non-zero, they must be relative primes, i.e.,
903 "bgcd($y, $mod)==1". '"NaN"' is returned when no modular
904 multiplicative inverse exists.
905
906 bmodpow()
907 $num->bmodpow($exp,$mod); # modular exponentiation
908 # ($num**$exp % $mod)
909
910 Returns the value of $num taken to the power $exp in the modulus
911 $mod using binary exponentiation. "bmodpow" is far superior to
912 writing
913
914 $num ** $exp % $mod
915
916 because it is much faster - it reduces internal variables into the
917 modulus whenever possible, so it operates on smaller numbers.
918
919 "bmodpow" also supports negative exponents.
920
921 bmodpow($num, -1, $mod)
922
923 is exactly equivalent to
924
925 bmodinv($num, $mod)
926
927 bpow()
928 $x->bpow($y); # power of arguments (x ** y)
929
930 "bpow()" (and the rounding functions) now modifies the first
931 argument and returns it, unlike the old code which left it alone
932 and only returned the result. This is to be consistent with
933 "badd()" etc. The first three modifies $x, the last one won't:
934
935 print bpow($x,$i),"\n"; # modify $x
936 print $x->bpow($i),"\n"; # ditto
937 print $x **= $i,"\n"; # the same
938 print $x ** $i,"\n"; # leave $x alone
939
940 The form "$x **= $y" is faster than "$x = $x ** $y;", though.
941
942 blog()
943 $x->blog($base, $accuracy); # logarithm of x to the base $base
944
945 If $base is not defined, Euler's number (e) is used:
946
947 print $x->blog(undef, 100); # log(x) to 100 digits
948
949 bexp()
950 $x->bexp($accuracy); # calculate e ** X
951
952 Calculates the expression "e ** $x" where "e" is Euler's number.
953
954 This method was added in v1.82 of Math::BigInt (April 2007).
955
956 See also "blog()".
957
958 bnok()
959 $x->bnok($y); # x over y (binomial coefficient n over k)
960
961 Calculates the binomial coefficient n over k, also called the
962 "choose" function, which is
963
964 ( n ) n!
965 | | = --------
966 ( k ) k!(n-k)!
967
968 when n and k are non-negative. This method implements the full
969 Kronenburg extension (Kronenburg, M.J. "The Binomial Coefficient
970 for Negative Arguments." 18 May 2011.
971 http://arxiv.org/abs/1105.3689/) illustrated by the following
972 pseudo-code:
973
974 if n >= 0 and k >= 0:
975 return binomial(n, k)
976 if k >= 0:
977 return (-1)^k*binomial(-n+k-1, k)
978 if k <= n:
979 return (-1)^(n-k)*binomial(-k-1, n-k)
980 else
981 return 0
982
983 The behaviour is identical to the behaviour of the Maple and
984 Mathematica function for negative integers n, k.
985
986 buparrow()
987 uparrow()
988 $a -> buparrow($n, $b); # modifies $a
989 $x = $a -> uparrow($n, $b); # does not modify $a
990
991 This method implements Knuth's up-arrow notation, where $n is a
992 non-negative integer representing the number of up-arrows. $n = 0
993 gives multiplication, $n = 1 gives exponentiation, $n = 2 gives
994 tetration, $n = 3 gives hexation etc. The following illustrates the
995 relation between the first values of $n.
996
997 See <https://en.wikipedia.org/wiki/Knuth%27s_up-arrow_notation>.
998
999 backermann()
1000 ackermann()
1001 $m -> backermann($n); # modifies $a
1002 $x = $m -> ackermann($n); # does not modify $a
1003
1004 This method implements the Ackermann function:
1005
1006 / n + 1 if m = 0
1007 A(m, n) = | A(m-1, 1) if m > 0 and n = 0
1008 \ A(m-1, A(m, n-1)) if m > 0 and n > 0
1009
1010 Its value grows rapidly, even for small inputs. For example, A(4,
1011 2) is an integer of 19729 decimal digits.
1012
1013 See https://en.wikipedia.org/wiki/Ackermann_function
1014
1015 bsin()
1016 my $x = Math::BigInt->new(1);
1017 print $x->bsin(100), "\n";
1018
1019 Calculate the sine of $x, modifying $x in place.
1020
1021 In Math::BigInt, unless upgrading is in effect, the result is
1022 truncated to an integer.
1023
1024 This method was added in v1.87 of Math::BigInt (June 2007).
1025
1026 bcos()
1027 my $x = Math::BigInt->new(1);
1028 print $x->bcos(100), "\n";
1029
1030 Calculate the cosine of $x, modifying $x in place.
1031
1032 In Math::BigInt, unless upgrading is in effect, the result is
1033 truncated to an integer.
1034
1035 This method was added in v1.87 of Math::BigInt (June 2007).
1036
1037 batan()
1038 my $x = Math::BigFloat->new(0.5);
1039 print $x->batan(100), "\n";
1040
1041 Calculate the arcus tangens of $x, modifying $x in place.
1042
1043 In Math::BigInt, unless upgrading is in effect, the result is
1044 truncated to an integer.
1045
1046 This method was added in v1.87 of Math::BigInt (June 2007).
1047
1048 batan2()
1049 my $x = Math::BigInt->new(1);
1050 my $y = Math::BigInt->new(1);
1051 print $y->batan2($x), "\n";
1052
1053 Calculate the arcus tangens of $y divided by $x, modifying $y in
1054 place.
1055
1056 In Math::BigInt, unless upgrading is in effect, the result is
1057 truncated to an integer.
1058
1059 This method was added in v1.87 of Math::BigInt (June 2007).
1060
1061 bsqrt()
1062 $x->bsqrt(); # calculate square root
1063
1064 "bsqrt()" returns the square root truncated to an integer.
1065
1066 If you want a better approximation of the square root, then use:
1067
1068 $x = Math::BigFloat->new(12);
1069 Math::BigFloat->precision(0);
1070 Math::BigFloat->round_mode('even');
1071 print $x->copy->bsqrt(),"\n"; # 4
1072
1073 Math::BigFloat->precision(2);
1074 print $x->bsqrt(),"\n"; # 3.46
1075 print $x->bsqrt(3),"\n"; # 3.464
1076
1077 broot()
1078 $x->broot($N);
1079
1080 Calculates the N'th root of $x.
1081
1082 bfac()
1083 $x->bfac(); # factorial of $x
1084
1085 Returns the factorial of $x, i.e., $x*($x-1)*($x-2)*...*2*1, the
1086 product of all positive integers up to and including $x. $x must be
1087 > -1. The factorial of N is commonly written as N!, or N!1, when
1088 using the multifactorial notation.
1089
1090 bdfac()
1091 $x->bdfac(); # double factorial of $x
1092
1093 Returns the double factorial of $x, i.e., $x*($x-2)*($x-4)*... $x
1094 must be > -2. The double factorial of N is commonly written as N!!,
1095 or N!2, when using the multifactorial notation.
1096
1097 btfac()
1098 $x->btfac(); # triple factorial of $x
1099
1100 Returns the triple factorial of $x, i.e., $x*($x-3)*($x-6)*... $x
1101 must be > -3. The triple factorial of N is commonly written as
1102 N!!!, or N!3, when using the multifactorial notation.
1103
1104 bmfac()
1105 $x->bmfac($k); # $k'th multifactorial of $x
1106
1107 Returns the multi-factorial of $x, i.e., $x*($x-$k)*($x-2*$k)*...
1108 $x must be > -$k. The multi-factorial of N is commonly written as
1109 N!K.
1110
1111 bfib()
1112 $F = $n->bfib(); # a single Fibonacci number
1113 @F = $n->bfib(); # a list of Fibonacci numbers
1114
1115 In scalar context, returns a single Fibonacci number. In list
1116 context, returns a list of Fibonacci numbers. The invocand is the
1117 last element in the output.
1118
1119 The Fibonacci sequence is defined by
1120
1121 F(0) = 0
1122 F(1) = 1
1123 F(n) = F(n-1) + F(n-2)
1124
1125 In list context, F(0) and F(n) is the first and last number in the
1126 output, respectively. For example, if $n is 12, then "@F =
1127 $n->bfib()" returns the following values, F(0) to F(12):
1128
1129 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144
1130
1131 The sequence can also be extended to negative index n using the re-
1132 arranged recurrence relation
1133
1134 F(n-2) = F(n) - F(n-1)
1135
1136 giving the bidirectional sequence
1137
1138 n -7 -6 -5 -4 -3 -2 -1 0 1 2 3 4 5 6 7
1139 F(n) 13 -8 5 -3 2 -1 1 0 1 1 2 3 5 8 13
1140
1141 If $n is -12, the following values, F(0) to F(12), are returned:
1142
1143 0, 1, -1, 2, -3, 5, -8, 13, -21, 34, -55, 89, -144
1144
1145 blucas()
1146 $F = $n->blucas(); # a single Lucas number
1147 @F = $n->blucas(); # a list of Lucas numbers
1148
1149 In scalar context, returns a single Lucas number. In list context,
1150 returns a list of Lucas numbers. The invocand is the last element
1151 in the output.
1152
1153 The Lucas sequence is defined by
1154
1155 L(0) = 2
1156 L(1) = 1
1157 L(n) = L(n-1) + L(n-2)
1158
1159 In list context, L(0) and L(n) is the first and last number in the
1160 output, respectively. For example, if $n is 12, then "@L =
1161 $n->blucas()" returns the following values, L(0) to L(12):
1162
1163 2, 1, 3, 4, 7, 11, 18, 29, 47, 76, 123, 199, 322
1164
1165 The sequence can also be extended to negative index n using the re-
1166 arranged recurrence relation
1167
1168 L(n-2) = L(n) - L(n-1)
1169
1170 giving the bidirectional sequence
1171
1172 n -7 -6 -5 -4 -3 -2 -1 0 1 2 3 4 5 6 7
1173 L(n) 29 -18 11 -7 4 -3 1 2 1 3 4 7 11 18 29
1174
1175 If $n is -12, the following values, L(0) to L(-12), are returned:
1176
1177 2, 1, -3, 4, -7, 11, -18, 29, -47, 76, -123, 199, -322
1178
1179 brsft()
1180 $x->brsft($n); # right shift $n places in base 2
1181 $x->brsft($n, $b); # right shift $n places in base $b
1182
1183 The latter is equivalent to
1184
1185 $x -> bdiv($b -> copy() -> bpow($n))
1186
1187 blsft()
1188 $x->blsft($n); # left shift $n places in base 2
1189 $x->blsft($n, $b); # left shift $n places in base $b
1190
1191 The latter is equivalent to
1192
1193 $x -> bmul($b -> copy() -> bpow($n))
1194
1195 Bitwise methods
1196 band()
1197 $x->band($y); # bitwise and
1198
1199 bior()
1200 $x->bior($y); # bitwise inclusive or
1201
1202 bxor()
1203 $x->bxor($y); # bitwise exclusive or
1204
1205 bnot()
1206 $x->bnot(); # bitwise not (two's complement)
1207
1208 Two's complement (bitwise not). This is equivalent to, but faster
1209 than,
1210
1211 $x->binc()->bneg();
1212
1213 Rounding methods
1214 round()
1215 $x->round($A,$P,$round_mode);
1216
1217 Round $x to accuracy $A or precision $P using the round mode
1218 $round_mode.
1219
1220 bround()
1221 $x->bround($N); # accuracy: preserve $N digits
1222
1223 Rounds $x to an accuracy of $N digits.
1224
1225 bfround()
1226 $x->bfround($N);
1227
1228 Rounds to a multiple of 10**$N. Examples:
1229
1230 Input N Result
1231
1232 123456.123456 3 123500
1233 123456.123456 2 123450
1234 123456.123456 -2 123456.12
1235 123456.123456 -3 123456.123
1236
1237 bfloor()
1238 $x->bfloor();
1239
1240 Round $x towards minus infinity, i.e., set $x to the largest
1241 integer less than or equal to $x.
1242
1243 bceil()
1244 $x->bceil();
1245
1246 Round $x towards plus infinity, i.e., set $x to the smallest
1247 integer greater than or equal to $x).
1248
1249 bint()
1250 $x->bint();
1251
1252 Round $x towards zero.
1253
1254 Other mathematical methods
1255 bgcd()
1256 $x -> bgcd($y); # GCD of $x and $y
1257 $x -> bgcd($y, $z, ...); # GCD of $x, $y, $z, ...
1258
1259 Returns the greatest common divisor (GCD).
1260
1261 blcm()
1262 $x -> blcm($y); # LCM of $x and $y
1263 $x -> blcm($y, $z, ...); # LCM of $x, $y, $z, ...
1264
1265 Returns the least common multiple (LCM).
1266
1267 Object property methods
1268 sign()
1269 $x->sign();
1270
1271 Return the sign, of $x, meaning either "+", "-", "-inf", "+inf" or
1272 NaN.
1273
1274 If you want $x to have a certain sign, use one of the following
1275 methods:
1276
1277 $x->babs(); # '+'
1278 $x->babs()->bneg(); # '-'
1279 $x->bnan(); # 'NaN'
1280 $x->binf(); # '+inf'
1281 $x->binf('-'); # '-inf'
1282
1283 digit()
1284 $x->digit($n); # return the nth digit, counting from right
1285
1286 If $n is negative, returns the digit counting from left.
1287
1288 digitsum()
1289 $x->digitsum();
1290
1291 Computes the sum of the base 10 digits and returns it.
1292
1293 bdigitsum()
1294 $x->bdigitsum();
1295
1296 Computes the sum of the base 10 digits and assigns the result to
1297 the invocand.
1298
1299 length()
1300 $x->length();
1301 ($xl, $fl) = $x->length();
1302
1303 Returns the number of digits in the decimal representation of the
1304 number. In list context, returns the length of the integer and
1305 fraction part. For Math::BigInt objects, the length of the fraction
1306 part is always 0.
1307
1308 The following probably doesn't do what you expect:
1309
1310 $c = Math::BigInt->new(123);
1311 print $c->length(),"\n"; # prints 30
1312
1313 It prints both the number of digits in the number and in the
1314 fraction part since print calls "length()" in list context. Use
1315 something like:
1316
1317 print scalar $c->length(),"\n"; # prints 3
1318
1319 mantissa()
1320 $x->mantissa();
1321
1322 Return the signed mantissa of $x as a Math::BigInt.
1323
1324 exponent()
1325 $x->exponent();
1326
1327 Return the exponent of $x as a Math::BigInt.
1328
1329 parts()
1330 $x->parts();
1331
1332 Returns the significand (mantissa) and the exponent as integers. In
1333 Math::BigFloat, both are returned as Math::BigInt objects.
1334
1335 sparts()
1336 Returns the significand (mantissa) and the exponent as integers. In
1337 scalar context, only the significand is returned. The significand
1338 is the integer with the smallest absolute value. The output of
1339 "sparts()" corresponds to the output from "bsstr()".
1340
1341 In Math::BigInt, this method is identical to "parts()".
1342
1343 nparts()
1344 Returns the significand (mantissa) and exponent corresponding to
1345 normalized notation. In scalar context, only the significand is
1346 returned. For finite non-zero numbers, the significand's absolute
1347 value is greater than or equal to 1 and less than 10. The output of
1348 "nparts()" corresponds to the output from "bnstr()". In
1349 Math::BigInt, if the significand can not be represented as an
1350 integer, upgrading is performed or NaN is returned.
1351
1352 eparts()
1353 Returns the significand (mantissa) and exponent corresponding to
1354 engineering notation. In scalar context, only the significand is
1355 returned. For finite non-zero numbers, the significand's absolute
1356 value is greater than or equal to 1 and less than 1000, and the
1357 exponent is a multiple of 3. The output of "eparts()" corresponds
1358 to the output from "bestr()". In Math::BigInt, if the significand
1359 can not be represented as an integer, upgrading is performed or NaN
1360 is returned.
1361
1362 dparts()
1363 Returns the integer part and the fraction part. If the fraction
1364 part can not be represented as an integer, upgrading is performed
1365 or NaN is returned. The output of "dparts()" corresponds to the
1366 output from "bdstr()".
1367
1368 fparts()
1369 Returns the smallest possible numerator and denominator so that the
1370 numerator divided by the denominator gives back the original value.
1371 For finite numbers, both values are integers. Mnemonic: fraction.
1372
1373 numerator()
1374 Together with "denominator()", returns the smallest integers so
1375 that the numerator divided by the denominator reproduces the
1376 original value. With Math::BigInt, numerator() simply returns a
1377 copy of the invocand.
1378
1379 denominator()
1380 Together with "numerator()", returns the smallest integers so that
1381 the numerator divided by the denominator reproduces the original
1382 value. With Math::BigInt, denominator() always returns either a 1
1383 or a NaN.
1384
1385 String conversion methods
1386 bstr()
1387 Returns a string representing the number using decimal notation. In
1388 Math::BigFloat, the output is zero padded according to the current
1389 accuracy or precision, if any of those are defined.
1390
1391 bsstr()
1392 Returns a string representing the number using scientific notation
1393 where both the significand (mantissa) and the exponent are
1394 integers. The output corresponds to the output from "sparts()".
1395
1396 123 is returned as "123e+0"
1397 1230 is returned as "123e+1"
1398 12300 is returned as "123e+2"
1399 12000 is returned as "12e+3"
1400 10000 is returned as "1e+4"
1401
1402 bnstr()
1403 Returns a string representing the number using normalized notation,
1404 the most common variant of scientific notation. For finite non-zero
1405 numbers, the absolute value of the significand is greater than or
1406 equal to 1 and less than 10. The output corresponds to the output
1407 from "nparts()".
1408
1409 123 is returned as "1.23e+2"
1410 1230 is returned as "1.23e+3"
1411 12300 is returned as "1.23e+4"
1412 12000 is returned as "1.2e+4"
1413 10000 is returned as "1e+4"
1414
1415 bestr()
1416 Returns a string representing the number using engineering
1417 notation. For finite non-zero numbers, the absolute value of the
1418 significand is greater than or equal to 1 and less than 1000, and
1419 the exponent is a multiple of 3. The output corresponds to the
1420 output from "eparts()".
1421
1422 123 is returned as "123e+0"
1423 1230 is returned as "1.23e+3"
1424 12300 is returned as "12.3e+3"
1425 12000 is returned as "12e+3"
1426 10000 is returned as "10e+3"
1427
1428 bdstr()
1429 Returns a string representing the number using decimal notation.
1430 The output corresponds to the output from "dparts()".
1431
1432 123 is returned as "123"
1433 1230 is returned as "1230"
1434 12300 is returned as "12300"
1435 12000 is returned as "12000"
1436 10000 is returned as "10000"
1437
1438 to_hex()
1439 $x->to_hex();
1440
1441 Returns a hexadecimal string representation of the number. See also
1442 from_hex().
1443
1444 to_bin()
1445 $x->to_bin();
1446
1447 Returns a binary string representation of the number. See also
1448 from_bin().
1449
1450 to_oct()
1451 $x->to_oct();
1452
1453 Returns an octal string representation of the number. See also
1454 from_oct().
1455
1456 to_bytes()
1457 $x = Math::BigInt->new("1667327589");
1458 $s = $x->to_bytes(); # $s = "cafe"
1459
1460 Returns a byte string representation of the number using big endian
1461 byte order. The invocand must be a non-negative, finite integer.
1462 See also from_bytes().
1463
1464 to_base()
1465 $x = Math::BigInt->new("250");
1466 $x->to_base(2); # returns "11111010"
1467 $x->to_base(8); # returns "372"
1468 $x->to_base(16); # returns "fa"
1469
1470 Returns a string representation of the number in the given base. If
1471 a collation sequence is given, the collation sequence determines
1472 which characters are used in the output.
1473
1474 Here are some more examples
1475
1476 $x = Math::BigInt->new("16")->to_base(3); # returns "121"
1477 $x = Math::BigInt->new("44027")->to_base(36); # returns "XYZ"
1478 $x = Math::BigInt->new("58314")->to_base(42); # returns "Why"
1479 $x = Math::BigInt->new("4")->to_base(2, "-|"); # returns "|--"
1480
1481 See from_base() for information and examples.
1482
1483 to_base_num()
1484 Converts the given number to the given base. This method is
1485 equivalent to "_to_base()", but returns numbers in an array rather
1486 than characters in a string. In the output, the first element is
1487 the most significant. Unlike "_to_base()", all input values may be
1488 arbitrarily large.
1489
1490 $x = Math::BigInt->new(13);
1491 $x->to_base_num(2); # returns [1, 1, 0, 1]
1492
1493 $x = Math::BigInt->new(65191);
1494 $x->to_base_num(128); # returns [3, 125, 39]
1495
1496 as_hex()
1497 $x->as_hex();
1498
1499 As, "to_hex()", but with a "0x" prefix.
1500
1501 as_bin()
1502 $x->as_bin();
1503
1504 As, "to_bin()", but with a "0b" prefix.
1505
1506 as_oct()
1507 $x->as_oct();
1508
1509 As, "to_oct()", but with a "0" prefix.
1510
1511 as_bytes()
1512 This is just an alias for "to_bytes()".
1513
1514 Other conversion methods
1515 numify()
1516 print $x->numify();
1517
1518 Returns a Perl scalar from $x. It is used automatically whenever a
1519 scalar is needed, for instance in array index operations.
1520
1521 Utility methods
1522 These utility methods are made public
1523
1524 dec_str_to_dec_flt_str()
1525 Takes a string representing any valid number using decimal notation
1526 and converts it to a string representing the same number using
1527 decimal floating point notation. The output consists of five parts
1528 joined together: the sign of the significand, the absolute value of
1529 the significand as the smallest possible integer, the letter "e",
1530 the sign of the exponent, and the absolute value of the exponent.
1531 If the input is invalid, nothing is returned.
1532
1533 $str2 = $class -> dec_str_to_dec_flt_str($str1);
1534
1535 Some examples
1536
1537 Input Output
1538 31400.00e-4 +314e-2
1539 -0.00012300e8 -123e+2
1540 0 +0e+0
1541
1542 hex_str_to_dec_flt_str()
1543 Takes a string representing any valid number using hexadecimal
1544 notation and converts it to a string representing the same number
1545 using decimal floating point notation. The output has the same
1546 format as that of "dec_str_to_dec_flt_str()".
1547
1548 $str2 = $class -> hex_str_to_dec_flt_str($str1);
1549
1550 Some examples
1551
1552 Input Output
1553 0xff +255e+0
1554
1555 Some examples
1556
1557 oct_str_to_dec_flt_str()
1558 Takes a string representing any valid number using octal notation
1559 and converts it to a string representing the same number using
1560 decimal floating point notation. The output has the same format as
1561 that of "dec_str_to_dec_flt_str()".
1562
1563 $str2 = $class -> oct_str_to_dec_flt_str($str1);
1564
1565 bin_str_to_dec_flt_str()
1566 Takes a string representing any valid number using binary notation
1567 and converts it to a string representing the same number using
1568 decimal floating point notation. The output has the same format as
1569 that of "dec_str_to_dec_flt_str()".
1570
1571 $str2 = $class -> bin_str_to_dec_flt_str($str1);
1572
1573 dec_str_to_dec_str()
1574 Takes a string representing any valid number using decimal notation
1575 and converts it to a string representing the same number using
1576 decimal notation. If the number represents an integer, the output
1577 consists of a sign and the absolute value. If the number represents
1578 a non-integer, the output consists of a sign, the integer part of
1579 the number, the decimal point ".", and the fraction part of the
1580 number without any trailing zeros. If the input is invalid, nothing
1581 is returned.
1582
1583 hex_str_to_dec_str()
1584 Takes a string representing any valid number using hexadecimal
1585 notation and converts it to a string representing the same number
1586 using decimal notation. The output has the same format as that of
1587 "dec_str_to_dec_str()".
1588
1589 oct_str_to_dec_str()
1590 Takes a string representing any valid number using octal notation
1591 and converts it to a string representing the same number using
1592 decimal notation. The output has the same format as that of
1593 "dec_str_to_dec_str()".
1594
1595 bin_str_to_dec_str()
1596 Takes a string representing any valid number using binary notation
1597 and converts it to a string representing the same number using
1598 decimal notation. The output has the same format as that of
1599 "dec_str_to_dec_str()".
1600
1602 Math::BigInt and Math::BigFloat have full support for accuracy and
1603 precision based rounding, both automatically after every operation, as
1604 well as manually.
1605
1606 This section describes the accuracy/precision handling in Math::BigInt
1607 and Math::BigFloat as it used to be and as it is now, complete with an
1608 explanation of all terms and abbreviations.
1609
1610 Not yet implemented things (but with correct description) are marked
1611 with '!', things that need to be answered are marked with '?'.
1612
1613 In the next paragraph follows a short description of terms used here
1614 (because these may differ from terms used by others people or
1615 documentation).
1616
1617 During the rest of this document, the shortcuts A (for accuracy), P
1618 (for precision), F (fallback) and R (rounding mode) are be used.
1619
1620 Precision P
1621 Precision is a fixed number of digits before (positive) or after
1622 (negative) the decimal point. For example, 123.45 has a precision of
1623 -2. 0 means an integer like 123 (or 120). A precision of 2 means at
1624 least two digits to the left of the decimal point are zero, so 123 with
1625 P = 1 becomes 120. Note that numbers with zeros before the decimal
1626 point may have different precisions, because 1200 can have P = 0, 1 or
1627 2 (depending on what the initial value was). It could also have p < 0,
1628 when the digits after the decimal point are zero.
1629
1630 The string output (of floating point numbers) is padded with zeros:
1631
1632 Initial value P A Result String
1633 ------------------------------------------------------------
1634 1234.01 -3 1000 1000
1635 1234 -2 1200 1200
1636 1234.5 -1 1230 1230
1637 1234.001 1 1234 1234.0
1638 1234.01 0 1234 1234
1639 1234.01 2 1234.01 1234.01
1640 1234.01 5 1234.01 1234.01000
1641
1642 For Math::BigInt objects, no padding occurs.
1643
1644 Accuracy A
1645 Number of significant digits. Leading zeros are not counted. A number
1646 may have an accuracy greater than the non-zero digits when there are
1647 zeros in it or trailing zeros. For example, 123.456 has A of 6, 10203
1648 has 5, 123.0506 has 7, 123.45000 has 8 and 0.000123 has 3.
1649
1650 The string output (of floating point numbers) is padded with zeros:
1651
1652 Initial value P A Result String
1653 ------------------------------------------------------------
1654 1234.01 3 1230 1230
1655 1234.01 6 1234.01 1234.01
1656 1234.1 8 1234.1 1234.1000
1657
1658 For Math::BigInt objects, no padding occurs.
1659
1660 Fallback F
1661 When both A and P are undefined, this is used as a fallback accuracy
1662 when dividing numbers.
1663
1664 Rounding mode R
1665 When rounding a number, different 'styles' or 'kinds' of rounding are
1666 possible. (Note that random rounding, as in Math::Round, is not
1667 implemented.)
1668
1669 Directed rounding
1670
1671 These round modes always round in the same direction.
1672
1673 'trunc'
1674 Round towards zero. Remove all digits following the rounding place,
1675 i.e., replace them with zeros. Thus, 987.65 rounded to tens (P=1)
1676 becomes 980, and rounded to the fourth significant digit becomes
1677 987.6 (A=4). 123.456 rounded to the second place after the decimal
1678 point (P=-2) becomes 123.46. This corresponds to the IEEE 754
1679 rounding mode 'roundTowardZero'.
1680
1681 Rounding to nearest
1682
1683 These rounding modes round to the nearest digit. They differ in how
1684 they determine which way to round in the ambiguous case when there is a
1685 tie.
1686
1687 'even'
1688 Round towards the nearest even digit, e.g., when rounding to
1689 nearest integer, -5.5 becomes -6, 4.5 becomes 4, but 4.501 becomes
1690 5. This corresponds to the IEEE 754 rounding mode
1691 'roundTiesToEven'.
1692
1693 'odd'
1694 Round towards the nearest odd digit, e.g., when rounding to nearest
1695 integer, 4.5 becomes 5, -5.5 becomes -5, but 5.501 becomes 6. This
1696 corresponds to the IEEE 754 rounding mode 'roundTiesToOdd'.
1697
1698 '+inf'
1699 Round towards plus infinity, i.e., always round up. E.g., when
1700 rounding to the nearest integer, 4.5 becomes 5, -5.5 becomes -5,
1701 and 4.501 also becomes 5. This corresponds to the IEEE 754 rounding
1702 mode 'roundTiesToPositive'.
1703
1704 '-inf'
1705 Round towards minus infinity, i.e., always round down. E.g., when
1706 rounding to the nearest integer, 4.5 becomes 4, -5.5 becomes -6,
1707 but 4.501 becomes 5. This corresponds to the IEEE 754 rounding mode
1708 'roundTiesToNegative'.
1709
1710 'zero'
1711 Round towards zero, i.e., round positive numbers down and negative
1712 numbers up. E.g., when rounding to the nearest integer, 4.5
1713 becomes 4, -5.5 becomes -5, but 4.501 becomes 5. This corresponds
1714 to the IEEE 754 rounding mode 'roundTiesToZero'.
1715
1716 'common'
1717 Round away from zero, i.e., round to the number with the largest
1718 absolute value. E.g., when rounding to the nearest integer, -1.5
1719 becomes -2, 1.5 becomes 2 and 1.49 becomes 1. This corresponds to
1720 the IEEE 754 rounding mode 'roundTiesToAway'.
1721
1722 The handling of A & P in MBI/MBF (the old core code shipped with Perl
1723 versions <= 5.7.2) is like this:
1724
1725 Precision
1726 * bfround($p) is able to round to $p number of digits after the decimal
1727 point
1728 * otherwise P is unused
1729
1730 Accuracy (significant digits)
1731 * bround($a) rounds to $a significant digits
1732 * only bdiv() and bsqrt() take A as (optional) parameter
1733 + other operations simply create the same number (bneg etc), or
1734 more (bmul) of digits
1735 + rounding/truncating is only done when explicitly calling one
1736 of bround or bfround, and never for Math::BigInt (not implemented)
1737 * bsqrt() simply hands its accuracy argument over to bdiv.
1738 * the documentation and the comment in the code indicate two
1739 different ways on how bdiv() determines the maximum number
1740 of digits it should calculate, and the actual code does yet
1741 another thing
1742 POD:
1743 max($Math::BigFloat::div_scale,length(dividend)+length(divisor))
1744 Comment:
1745 result has at most max(scale, length(dividend), length(divisor)) digits
1746 Actual code:
1747 scale = max(scale, length(dividend)-1,length(divisor)-1);
1748 scale += length(divisor) - length(dividend);
1749 So for lx = 3, ly = 9, scale = 10, scale will actually be 16 (10
1750 So for lx = 3, ly = 9, scale = 10, scale will actually be 16
1751 (10+9-3). Actually, the 'difference' added to the scale is cal-
1752 culated from the number of "significant digits" in dividend and
1753 divisor, which is derived by looking at the length of the man-
1754 tissa. Which is wrong, since it includes the + sign (oops) and
1755 actually gets 2 for '+100' and 4 for '+101'. Oops again. Thus
1756 124/3 with div_scale=1 will get you '41.3' based on the strange
1757 assumption that 124 has 3 significant digits, while 120/7 will
1758 get you '17', not '17.1' since 120 is thought to have 2 signif-
1759 icant digits. The rounding after the division then uses the
1760 remainder and $y to determine whether it must round up or down.
1761 ? I have no idea which is the right way. That's why I used a slightly more
1762 ? simple scheme and tweaked the few failing testcases to match it.
1763
1764 This is how it works now:
1765
1766 Setting/Accessing
1767 * You can set the A global via Math::BigInt->accuracy() or
1768 Math::BigFloat->accuracy() or whatever class you are using.
1769 * You can also set P globally by using Math::SomeClass->precision()
1770 likewise.
1771 * Globals are classwide, and not inherited by subclasses.
1772 * to undefine A, use Math::SomeClass->accuracy(undef);
1773 * to undefine P, use Math::SomeClass->precision(undef);
1774 * Setting Math::SomeClass->accuracy() clears automatically
1775 Math::SomeClass->precision(), and vice versa.
1776 * To be valid, A must be > 0, P can have any value.
1777 * If P is negative, this means round to the P'th place to the right of the
1778 decimal point; positive values mean to the left of the decimal point.
1779 P of 0 means round to integer.
1780 * to find out the current global A, use Math::SomeClass->accuracy()
1781 * to find out the current global P, use Math::SomeClass->precision()
1782 * use $x->accuracy() respective $x->precision() for the local
1783 setting of $x.
1784 * Please note that $x->accuracy() respective $x->precision()
1785 return eventually defined global A or P, when $x's A or P is not
1786 set.
1787
1788 Creating numbers
1789 * When you create a number, you can give the desired A or P via:
1790 $x = Math::BigInt->new($number,$A,$P);
1791 * Only one of A or P can be defined, otherwise the result is NaN
1792 * If no A or P is give ($x = Math::BigInt->new($number) form), then the
1793 globals (if set) will be used. Thus changing the global defaults later on
1794 will not change the A or P of previously created numbers (i.e., A and P of
1795 $x will be what was in effect when $x was created)
1796 * If given undef for A and P, NO rounding will occur, and the globals will
1797 NOT be used. This is used by subclasses to create numbers without
1798 suffering rounding in the parent. Thus a subclass is able to have its own
1799 globals enforced upon creation of a number by using
1800 $x = Math::BigInt->new($number,undef,undef):
1801
1802 use Math::BigInt::SomeSubclass;
1803 use Math::BigInt;
1804
1805 Math::BigInt->accuracy(2);
1806 Math::BigInt::SomeSubclass->accuracy(3);
1807 $x = Math::BigInt::SomeSubclass->new(1234);
1808
1809 $x is now 1230, and not 1200. A subclass might choose to implement
1810 this otherwise, e.g. falling back to the parent's A and P.
1811
1812 Usage
1813 * If A or P are enabled/defined, they are used to round the result of each
1814 operation according to the rules below
1815 * Negative P is ignored in Math::BigInt, since Math::BigInt objects never
1816 have digits after the decimal point
1817 * Math::BigFloat uses Math::BigInt internally, but setting A or P inside
1818 Math::BigInt as globals does not tamper with the parts of a Math::BigFloat.
1819 A flag is used to mark all Math::BigFloat numbers as 'never round'.
1820
1821 Precedence
1822 * It only makes sense that a number has only one of A or P at a time.
1823 If you set either A or P on one object, or globally, the other one will
1824 be automatically cleared.
1825 * If two objects are involved in an operation, and one of them has A in
1826 effect, and the other P, this results in an error (NaN).
1827 * A takes precedence over P (Hint: A comes before P).
1828 If neither of them is defined, nothing is used, i.e. the result will have
1829 as many digits as it can (with an exception for bdiv/bsqrt) and will not
1830 be rounded.
1831 * There is another setting for bdiv() (and thus for bsqrt()). If neither of
1832 A or P is defined, bdiv() will use a fallback (F) of $div_scale digits.
1833 If either the dividend's or the divisor's mantissa has more digits than
1834 the value of F, the higher value will be used instead of F.
1835 This is to limit the digits (A) of the result (just consider what would
1836 happen with unlimited A and P in the case of 1/3 :-)
1837 * bdiv will calculate (at least) 4 more digits than required (determined by
1838 A, P or F), and, if F is not used, round the result
1839 (this will still fail in the case of a result like 0.12345000000001 with A
1840 or P of 5, but this can not be helped - or can it?)
1841 * Thus you can have the math done by on Math::Big* class in two modi:
1842 + never round (this is the default):
1843 This is done by setting A and P to undef. No math operation
1844 will round the result, with bdiv() and bsqrt() as exceptions to guard
1845 against overflows. You must explicitly call bround(), bfround() or
1846 round() (the latter with parameters).
1847 Note: Once you have rounded a number, the settings will 'stick' on it
1848 and 'infect' all other numbers engaged in math operations with it, since
1849 local settings have the highest precedence. So, to get SaferRound[tm],
1850 use a copy() before rounding like this:
1851
1852 $x = Math::BigFloat->new(12.34);
1853 $y = Math::BigFloat->new(98.76);
1854 $z = $x * $y; # 1218.6984
1855 print $x->copy()->bround(3); # 12.3 (but A is now 3!)
1856 $z = $x * $y; # still 1218.6984, without
1857 # copy would have been 1210!
1858
1859 + round after each op:
1860 After each single operation (except for testing like is_zero()), the
1861 method round() is called and the result is rounded appropriately. By
1862 setting proper values for A and P, you can have all-the-same-A or
1863 all-the-same-P modes. For example, Math::Currency might set A to undef,
1864 and P to -2, globally.
1865
1866 ?Maybe an extra option that forbids local A & P settings would be in order,
1867 ?so that intermediate rounding does not 'poison' further math?
1868
1869 Overriding globals
1870 * you will be able to give A, P and R as an argument to all the calculation
1871 routines; the second parameter is A, the third one is P, and the fourth is
1872 R (shift right by one for binary operations like badd). P is used only if
1873 the first parameter (A) is undefined. These three parameters override the
1874 globals in the order detailed as follows, i.e. the first defined value
1875 wins:
1876 (local: per object, global: global default, parameter: argument to sub)
1877 + parameter A
1878 + parameter P
1879 + local A (if defined on both of the operands: smaller one is taken)
1880 + local P (if defined on both of the operands: bigger one is taken)
1881 + global A
1882 + global P
1883 + global F
1884 * bsqrt() will hand its arguments to bdiv(), as it used to, only now for two
1885 arguments (A and P) instead of one
1886
1887 Local settings
1888 * You can set A or P locally by using $x->accuracy() or
1889 $x->precision()
1890 and thus force different A and P for different objects/numbers.
1891 * Setting A or P this way immediately rounds $x to the new value.
1892 * $x->accuracy() clears $x->precision(), and vice versa.
1893
1894 Rounding
1895 * the rounding routines will use the respective global or local settings.
1896 bround() is for accuracy rounding, while bfround() is for precision
1897 * the two rounding functions take as the second parameter one of the
1898 following rounding modes (R):
1899 'even', 'odd', '+inf', '-inf', 'zero', 'trunc', 'common'
1900 * you can set/get the global R by using Math::SomeClass->round_mode()
1901 or by setting $Math::SomeClass::round_mode
1902 * after each operation, $result->round() is called, and the result may
1903 eventually be rounded (that is, if A or P were set either locally,
1904 globally or as parameter to the operation)
1905 * to manually round a number, call $x->round($A,$P,$round_mode);
1906 this will round the number by using the appropriate rounding function
1907 and then normalize it.
1908 * rounding modifies the local settings of the number:
1909
1910 $x = Math::BigFloat->new(123.456);
1911 $x->accuracy(5);
1912 $x->bround(4);
1913
1914 Here 4 takes precedence over 5, so 123.5 is the result and $x->accuracy()
1915 will be 4 from now on.
1916
1917 Default values
1918 * R: 'even'
1919 * F: 40
1920 * A: undef
1921 * P: undef
1922
1923 Remarks
1924 * The defaults are set up so that the new code gives the same results as
1925 the old code (except in a few cases on bdiv):
1926 + Both A and P are undefined and thus will not be used for rounding
1927 after each operation.
1928 + round() is thus a no-op, unless given extra parameters A and P
1929
1931 While Math::BigInt has extensive handling of inf and NaN, certain
1932 quirks remain.
1933
1934 oct()/hex()
1935 These perl routines currently (as of Perl v.5.8.6) cannot handle
1936 passed inf.
1937
1938 te@linux:~> perl -wle 'print 2 ** 3333'
1939 Inf
1940 te@linux:~> perl -wle 'print 2 ** 3333 == 2 ** 3333'
1941 1
1942 te@linux:~> perl -wle 'print oct(2 ** 3333)'
1943 0
1944 te@linux:~> perl -wle 'print hex(2 ** 3333)'
1945 Illegal hexadecimal digit 'I' ignored at -e line 1.
1946 0
1947
1948 The same problems occur if you pass them Math::BigInt->binf()
1949 objects. Since overloading these routines is not possible, this
1950 cannot be fixed from Math::BigInt.
1951
1953 You should neither care about nor depend on the internal
1954 representation; it might change without notice. Use ONLY method calls
1955 like "$x->sign();" instead relying on the internal representation.
1956
1957 MATH LIBRARY
1958 The mathematical computations are performed by a backend library. It is
1959 not required to specify which backend library to use, but some backend
1960 libraries are much faster than the default library.
1961
1962 The default library
1963
1964 The default library is Math::BigInt::Calc, which is implemented in pure
1965 Perl and hence does not require a compiler.
1966
1967 Specifying a library
1968
1969 The simple case
1970
1971 use Math::BigInt;
1972
1973 is equivalent to saying
1974
1975 use Math::BigInt try => 'Calc';
1976
1977 You can use a different backend library with, e.g.,
1978
1979 use Math::BigInt try => 'GMP';
1980
1981 which attempts to load the Math::BigInt::GMP library, and falls back to
1982 the default library if the specified library can't be loaded.
1983
1984 Multiple libraries can be specified by separating them by a comma,
1985 e.g.,
1986
1987 use Math::BigInt try => 'GMP,Pari';
1988
1989 If you request a specific set of libraries and do not allow fallback to
1990 the default library, specify them using "only",
1991
1992 use Math::BigInt only => 'GMP,Pari';
1993
1994 If you prefer a specific set of libraries, but want to see a warning if
1995 the fallback library is used, specify them using "lib",
1996
1997 use Math::BigInt lib => 'GMP,Pari';
1998
1999 The following first tries to find Math::BigInt::Foo, then
2000 Math::BigInt::Bar, and if this also fails, reverts to
2001 Math::BigInt::Calc:
2002
2003 use Math::BigInt try => 'Foo,Math::BigInt::Bar';
2004
2005 Which library to use?
2006
2007 Note: General purpose packages should not be explicit about the library
2008 to use; let the script author decide which is best.
2009
2010 Math::BigInt::GMP, Math::BigInt::Pari, and Math::BigInt::GMPz are in
2011 cases involving big numbers much faster than Math::BigInt::Calc.
2012 However these libraries are slower when dealing with very small numbers
2013 (less than about 20 digits) and when converting very large numbers to
2014 decimal (for instance for printing, rounding, calculating their length
2015 in decimal etc.).
2016
2017 So please select carefully what library you want to use.
2018
2019 Different low-level libraries use different formats to store the
2020 numbers, so mixing them won't work. You should not depend on the number
2021 having a specific internal format.
2022
2023 See the respective math library module documentation for further
2024 details.
2025
2026 Loading multiple libraries
2027
2028 The first library that is successfully loaded is the one that will be
2029 used. Any further attempts at loading a different module will be
2030 ignored. This is to avoid the situation where module A requires math
2031 library X, and module B requires math library Y, causing modules A and
2032 B to be incompatible. For example,
2033
2034 use Math::BigInt; # loads default "Calc"
2035 use Math::BigFloat only => "GMP"; # ignores "GMP"
2036
2037 SIGN
2038 The sign is either '+', '-', 'NaN', '+inf' or '-inf'.
2039
2040 A sign of 'NaN' is used to represent the result when input arguments
2041 are not numbers or as a result of 0/0. '+inf' and '-inf' represent plus
2042 respectively minus infinity. You get '+inf' when dividing a positive
2043 number by 0, and '-inf' when dividing any negative number by 0.
2044
2046 use Math::BigInt;
2047
2048 sub bigint { Math::BigInt->new(shift); }
2049
2050 $x = Math::BigInt->bstr("1234") # string "1234"
2051 $x = "$x"; # same as bstr()
2052 $x = Math::BigInt->bneg("1234"); # Math::BigInt "-1234"
2053 $x = Math::BigInt->babs("-12345"); # Math::BigInt "12345"
2054 $x = Math::BigInt->bnorm("-0.00"); # Math::BigInt "0"
2055 $x = bigint(1) + bigint(2); # Math::BigInt "3"
2056 $x = bigint(1) + "2"; # ditto ("2" becomes a Math::BigInt)
2057 $x = bigint(1); # Math::BigInt "1"
2058 $x = $x + 5 / 2; # Math::BigInt "3"
2059 $x = $x ** 3; # Math::BigInt "27"
2060 $x *= 2; # Math::BigInt "54"
2061 $x = Math::BigInt->new(0); # Math::BigInt "0"
2062 $x--; # Math::BigInt "-1"
2063 $x = Math::BigInt->badd(4,5) # Math::BigInt "9"
2064 print $x->bsstr(); # 9e+0
2065
2066 Examples for rounding:
2067
2068 use Math::BigFloat;
2069 use Test::More;
2070
2071 $x = Math::BigFloat->new(123.4567);
2072 $y = Math::BigFloat->new(123.456789);
2073 Math::BigFloat->accuracy(4); # no more A than 4
2074
2075 is ($x->copy()->bround(),123.4); # even rounding
2076 print $x->copy()->bround(),"\n"; # 123.4
2077 Math::BigFloat->round_mode('odd'); # round to odd
2078 print $x->copy()->bround(),"\n"; # 123.5
2079 Math::BigFloat->accuracy(5); # no more A than 5
2080 Math::BigFloat->round_mode('odd'); # round to odd
2081 print $x->copy()->bround(),"\n"; # 123.46
2082 $y = $x->copy()->bround(4),"\n"; # A = 4: 123.4
2083 print "$y, ",$y->accuracy(),"\n"; # 123.4, 4
2084
2085 Math::BigFloat->accuracy(undef); # A not important now
2086 Math::BigFloat->precision(2); # P important
2087 print $x->copy()->bnorm(),"\n"; # 123.46
2088 print $x->copy()->bround(),"\n"; # 123.46
2089
2090 Examples for converting:
2091
2092 my $x = Math::BigInt->new('0b1'.'01' x 123);
2093 print "bin: ",$x->as_bin()," hex:",$x->as_hex()," dec: ",$x,"\n";
2094
2096 After "use Math::BigInt ':constant'" all numeric literals in the given
2097 scope are converted to "Math::BigInt" objects. This conversion happens
2098 at compile time. Every non-integer is convert to a NaN.
2099
2100 For example,
2101
2102 perl -MMath::BigInt=:constant -le 'print 2**150'
2103
2104 prints the exact value of "2**150". Note that without conversion of
2105 constants to objects the expression "2**150" is calculated using Perl
2106 scalars, which leads to an inaccurate result.
2107
2108 Please note that strings are not affected, so that
2109
2110 use Math::BigInt qw/:constant/;
2111
2112 $x = "1234567890123456789012345678901234567890"
2113 + "123456789123456789";
2114
2115 does give you what you expect. You need an explicit Math::BigInt->new()
2116 around at least one of the operands. You should also quote large
2117 constants to prevent loss of precision:
2118
2119 use Math::BigInt;
2120
2121 $x = Math::BigInt->new("1234567889123456789123456789123456789");
2122
2123 Without the quotes Perl first converts the large number to a floating
2124 point constant at compile time, and then converts the result to a
2125 Math::BigInt object at run time, which results in an inaccurate result.
2126
2127 Hexadecimal, octal, and binary floating point literals
2128 Perl (and this module) accepts hexadecimal, octal, and binary floating
2129 point literals, but use them with care with Perl versions before
2130 v5.32.0, because some versions of Perl silently give the wrong result.
2131 Below are some examples of different ways to write the number decimal
2132 314.
2133
2134 Hexadecimal floating point literals:
2135
2136 0x1.3ap+8 0X1.3AP+8
2137 0x1.3ap8 0X1.3AP8
2138 0x13a0p-4 0X13A0P-4
2139
2140 Octal floating point literals (with "0" prefix):
2141
2142 01.164p+8 01.164P+8
2143 01.164p8 01.164P8
2144 011640p-4 011640P-4
2145
2146 Octal floating point literals (with "0o" prefix) (requires v5.34.0):
2147
2148 0o1.164p+8 0O1.164P+8
2149 0o1.164p8 0O1.164P8
2150 0o11640p-4 0O11640P-4
2151
2152 Binary floating point literals:
2153
2154 0b1.0011101p+8 0B1.0011101P+8
2155 0b1.0011101p8 0B1.0011101P8
2156 0b10011101000p-2 0B10011101000P-2
2157
2159 Using the form $x += $y; etc over $x = $x + $y is faster, since a copy
2160 of $x must be made in the second case. For long numbers, the copy can
2161 eat up to 20% of the work (in the case of addition/subtraction, less
2162 for multiplication/division). If $y is very small compared to $x, the
2163 form $x += $y is MUCH faster than $x = $x + $y since making the copy of
2164 $x takes more time then the actual addition.
2165
2166 With a technique called copy-on-write, the cost of copying with
2167 overload could be minimized or even completely avoided. A test
2168 implementation of COW did show performance gains for overloaded math,
2169 but introduced a performance loss due to a constant overhead for all
2170 other operations. So Math::BigInt does currently not COW.
2171
2172 The rewritten version of this module (vs. v0.01) is slower on certain
2173 operations, like "new()", "bstr()" and "numify()". The reason are that
2174 it does now more work and handles much more cases. The time spent in
2175 these operations is usually gained in the other math operations so that
2176 code on the average should get (much) faster. If they don't, please
2177 contact the author.
2178
2179 Some operations may be slower for small numbers, but are significantly
2180 faster for big numbers. Other operations are now constant (O(1), like
2181 "bneg()", "babs()" etc), instead of O(N) and thus nearly always take
2182 much less time. These optimizations were done on purpose.
2183
2184 If you find the Calc module to slow, try to install any of the
2185 replacement modules and see if they help you.
2186
2187 Alternative math libraries
2188 You can use an alternative library to drive Math::BigInt. See the
2189 section "MATH LIBRARY" for more information.
2190
2191 For more benchmark results see
2192 <http://bloodgate.com/perl/benchmarks.html>.
2193
2195 Subclassing Math::BigInt
2196 The basic design of Math::BigInt allows simple subclasses with very
2197 little work, as long as a few simple rules are followed:
2198
2199 • The public API must remain consistent, i.e. if a sub-class is
2200 overloading addition, the sub-class must use the same name, in this
2201 case badd(). The reason for this is that Math::BigInt is optimized
2202 to call the object methods directly.
2203
2204 • The private object hash keys like "$x->{sign}" may not be changed,
2205 but additional keys can be added, like "$x->{_custom}".
2206
2207 • Accessor functions are available for all existing object hash keys
2208 and should be used instead of directly accessing the internal hash
2209 keys. The reason for this is that Math::BigInt itself has a
2210 pluggable interface which permits it to support different storage
2211 methods.
2212
2213 More complex sub-classes may have to replicate more of the logic
2214 internal of Math::BigInt if they need to change more basic behaviors. A
2215 subclass that needs to merely change the output only needs to overload
2216 "bstr()".
2217
2218 All other object methods and overloaded functions can be directly
2219 inherited from the parent class.
2220
2221 At the very minimum, any subclass needs to provide its own "new()" and
2222 can store additional hash keys in the object. There are also some
2223 package globals that must be defined, e.g.:
2224
2225 # Globals
2226 $accuracy = undef;
2227 $precision = -2; # round to 2 decimal places
2228 $round_mode = 'even';
2229 $div_scale = 40;
2230
2231 Additionally, you might want to provide the following two globals to
2232 allow auto-upgrading and auto-downgrading to work correctly:
2233
2234 $upgrade = undef;
2235 $downgrade = undef;
2236
2237 This allows Math::BigInt to correctly retrieve package globals from the
2238 subclass, like $SubClass::precision. See t/Math/BigInt/Subclass.pm or
2239 t/Math/BigFloat/SubClass.pm completely functional subclass examples.
2240
2241 Don't forget to
2242
2243 use overload;
2244
2245 in your subclass to automatically inherit the overloading from the
2246 parent. If you like, you can change part of the overloading, look at
2247 Math::String for an example.
2248
2250 When used like this:
2251
2252 use Math::BigInt upgrade => 'Foo::Bar';
2253
2254 certain operations 'upgrade' their calculation and thus the result to
2255 the class Foo::Bar. Usually this is used in conjunction with
2256 Math::BigFloat:
2257
2258 use Math::BigInt upgrade => 'Math::BigFloat';
2259
2260 As a shortcut, you can use the module bignum:
2261
2262 use bignum;
2263
2264 Also good for one-liners:
2265
2266 perl -Mbignum -le 'print 2 ** 255'
2267
2268 This makes it possible to mix arguments of different classes (as in 2.5
2269 + 2) as well es preserve accuracy (as in sqrt(3)).
2270
2271 Beware: This feature is not fully implemented yet.
2272
2273 Auto-upgrade
2274 The following methods upgrade themselves unconditionally; that is if
2275 upgrade is in effect, they always hands up their work:
2276
2277 div bsqrt blog bexp bpi bsin bcos batan batan2
2278
2279 All other methods upgrade themselves only when one (or all) of their
2280 arguments are of the class mentioned in $upgrade.
2281
2283 "Math::BigInt" exports nothing by default, but can export the following
2284 methods:
2285
2286 bgcd
2287 blcm
2288
2290 Some things might not work as you expect them. Below is documented what
2291 is known to be troublesome:
2292
2293 Comparing numbers as strings
2294 Both "bstr()" and "bsstr()" as well as stringify via overload drop
2295 the leading '+'. This is to be consistent with Perl and to make
2296 "cmp" (especially with overloading) to work as you expect. It also
2297 solves problems with "Test.pm" and Test::More, which stringify
2298 arguments before comparing them.
2299
2300 Mark Biggar said, when asked about to drop the '+' altogether, or
2301 make only "cmp" work:
2302
2303 I agree (with the first alternative), don't add the '+' on positive
2304 numbers. It's not as important anymore with the new internal form
2305 for numbers. It made doing things like abs and neg easier, but
2306 those have to be done differently now anyway.
2307
2308 So, the following examples now works as expected:
2309
2310 use Test::More tests => 1;
2311 use Math::BigInt;
2312
2313 my $x = Math::BigInt -> new(3*3);
2314 my $y = Math::BigInt -> new(3*3);
2315
2316 is($x,3*3, 'multiplication');
2317 print "$x eq 9" if $x eq $y;
2318 print "$x eq 9" if $x eq '9';
2319 print "$x eq 9" if $x eq 3*3;
2320
2321 Additionally, the following still works:
2322
2323 print "$x == 9" if $x == $y;
2324 print "$x == 9" if $x == 9;
2325 print "$x == 9" if $x == 3*3;
2326
2327 There is now a "bsstr()" method to get the string in scientific
2328 notation aka 1e+2 instead of 100. Be advised that overloaded 'eq'
2329 always uses bstr() for comparison, but Perl represents some numbers
2330 as 100 and others as 1e+308. If in doubt, convert both arguments
2331 to Math::BigInt before comparing them as strings:
2332
2333 use Test::More tests => 3;
2334 use Math::BigInt;
2335
2336 $x = Math::BigInt->new('1e56'); $y = 1e56;
2337 is($x,$y); # fails
2338 is($x->bsstr(),$y); # okay
2339 $y = Math::BigInt->new($y);
2340 is($x,$y); # okay
2341
2342 Alternatively, simply use "<=>" for comparisons, this always gets
2343 it right. There is not yet a way to get a number automatically
2344 represented as a string that matches exactly the way Perl
2345 represents it.
2346
2347 See also the section about "Infinity and Not a Number" for problems
2348 in comparing NaNs.
2349
2350 int()
2351 "int()" returns (at least for Perl v5.7.1 and up) another
2352 Math::BigInt, not a Perl scalar:
2353
2354 $x = Math::BigInt->new(123);
2355 $y = int($x); # 123 as a Math::BigInt
2356 $x = Math::BigFloat->new(123.45);
2357 $y = int($x); # 123 as a Math::BigFloat
2358
2359 If you want a real Perl scalar, use "numify()":
2360
2361 $y = $x->numify(); # 123 as a scalar
2362
2363 This is seldom necessary, though, because this is done
2364 automatically, like when you access an array:
2365
2366 $z = $array[$x]; # does work automatically
2367
2368 Modifying and =
2369 Beware of:
2370
2371 $x = Math::BigFloat->new(5);
2372 $y = $x;
2373
2374 This makes a second reference to the same object and stores it in
2375 $y. Thus anything that modifies $x (except overloaded operators)
2376 also modifies $y, and vice versa. Or in other words, "=" is only
2377 safe if you modify your Math::BigInt objects only via overloaded
2378 math. As soon as you use a method call it breaks:
2379
2380 $x->bmul(2);
2381 print "$x, $y\n"; # prints '10, 10'
2382
2383 If you want a true copy of $x, use:
2384
2385 $y = $x->copy();
2386
2387 You can also chain the calls like this, this first makes a copy and
2388 then multiply it by 2:
2389
2390 $y = $x->copy()->bmul(2);
2391
2392 See also the documentation for overload.pm regarding "=".
2393
2394 Overloading -$x
2395 The following:
2396
2397 $x = -$x;
2398
2399 is slower than
2400
2401 $x->bneg();
2402
2403 since overload calls "sub($x,0,1);" instead of "neg($x)". The first
2404 variant needs to preserve $x since it does not know that it later
2405 gets overwritten. This makes a copy of $x and takes O(N), but
2406 $x->bneg() is O(1).
2407
2408 Mixing different object types
2409 With overloaded operators, it is the first (dominating) operand
2410 that determines which method is called. Here are some examples
2411 showing what actually gets called in various cases.
2412
2413 use Math::BigInt;
2414 use Math::BigFloat;
2415
2416 $mbf = Math::BigFloat->new(5);
2417 $mbi2 = Math::BigInt->new(5);
2418 $mbi = Math::BigInt->new(2);
2419 # what actually gets called:
2420 $float = $mbf + $mbi; # $mbf->badd($mbi)
2421 $float = $mbf / $mbi; # $mbf->bdiv($mbi)
2422 $integer = $mbi + $mbf; # $mbi->badd($mbf)
2423 $integer = $mbi2 / $mbi; # $mbi2->bdiv($mbi)
2424 $integer = $mbi2 / $mbf; # $mbi2->bdiv($mbf)
2425
2426 For instance, Math::BigInt->bdiv() always returns a Math::BigInt,
2427 regardless of whether the second operant is a Math::BigFloat. To
2428 get a Math::BigFloat you either need to call the operation
2429 manually, make sure each operand already is a Math::BigFloat, or
2430 cast to that type via Math::BigFloat->new():
2431
2432 $float = Math::BigFloat->new($mbi2) / $mbi; # = 2.5
2433
2434 Beware of casting the entire expression, as this would cast the
2435 result, at which point it is too late:
2436
2437 $float = Math::BigFloat->new($mbi2 / $mbi); # = 2
2438
2439 Beware also of the order of more complicated expressions like:
2440
2441 $integer = ($mbi2 + $mbi) / $mbf; # int / float => int
2442 $integer = $mbi2 / Math::BigFloat->new($mbi); # ditto
2443
2444 If in doubt, break the expression into simpler terms, or cast all
2445 operands to the desired resulting type.
2446
2447 Scalar values are a bit different, since:
2448
2449 $float = 2 + $mbf;
2450 $float = $mbf + 2;
2451
2452 both result in the proper type due to the way the overloaded math
2453 works.
2454
2455 This section also applies to other overloaded math packages, like
2456 Math::String.
2457
2458 One solution to you problem might be autoupgrading|upgrading. See
2459 the pragmas bignum, bigint and bigrat for an easy way to do this.
2460
2462 Please report any bugs or feature requests to "bug-math-bigint at
2463 rt.cpan.org", or through the web interface at
2464 <https://rt.cpan.org/Ticket/Create.html?Queue=Math-BigInt> (requires
2465 login). We will be notified, and then you'll automatically be notified
2466 of progress on your bug as I make changes.
2467
2469 You can find documentation for this module with the perldoc command.
2470
2471 perldoc Math::BigInt
2472
2473 You can also look for information at:
2474
2475 • GitHub
2476
2477 <https://github.com/pjacklam/p5-Math-BigInt>
2478
2479 • RT: CPAN's request tracker
2480
2481 <https://rt.cpan.org/Dist/Display.html?Name=Math-BigInt>
2482
2483 • MetaCPAN
2484
2485 <https://metacpan.org/release/Math-BigInt>
2486
2487 • CPAN Testers Matrix
2488
2489 <http://matrix.cpantesters.org/?dist=Math-BigInt>
2490
2491 • CPAN Ratings
2492
2493 <https://cpanratings.perl.org/dist/Math-BigInt>
2494
2495 • The Bignum mailing list
2496
2497 • Post to mailing list
2498
2499 "bignum at lists.scsys.co.uk"
2500
2501 • View mailing list
2502
2503 <http://lists.scsys.co.uk/pipermail/bignum/>
2504
2505 • Subscribe/Unsubscribe
2506
2507 <http://lists.scsys.co.uk/cgi-bin/mailman/listinfo/bignum>
2508
2510 This program is free software; you may redistribute it and/or modify it
2511 under the same terms as Perl itself.
2512
2514 Math::BigFloat and Math::BigRat as well as the backends
2515 Math::BigInt::FastCalc, Math::BigInt::GMP, and Math::BigInt::Pari.
2516
2517 The pragmas bignum, bigint and bigrat also might be of interest because
2518 they solve the autoupgrading/downgrading issue, at least partly.
2519
2521 • Mark Biggar, overloaded interface by Ilya Zakharevich, 1996-2001.
2522
2523 • Completely rewritten by Tels <http://bloodgate.com>, 2001-2008.
2524
2525 • Florian Ragwitz <flora@cpan.org>, 2010.
2526
2527 • Peter John Acklam <pjacklam@gmail.com>, 2011-.
2528
2529 Many people contributed in one or more ways to the final beast, see the
2530 file CREDITS for an (incomplete) list. If you miss your name, please
2531 drop me a mail. Thank you!
2532
2533
2534
2535perl v5.34.1 2022-04-13 Math::BigInt(3)