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