1Math::BigInt(3pm) Perl Programmers Reference Guide Math::BigInt(3pm)
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 will fall back to
13 # pure Perl if the GMP library is not installed):
14 # (See also the L<MATH LIBRARY> section!)
15
16 # will warn 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 # Number creation
30 my $x = Math::BigInt->new($str); # defaults to 0
31 my $y = $x->copy(); # make a true copy
32 my $nan = Math::BigInt->bnan(); # create a NotANumber
33 my $zero = Math::BigInt->bzero(); # create a +0
34 my $inf = Math::BigInt->binf(); # create a +inf
35 my $inf = Math::BigInt->binf('-'); # create a -inf
36 my $one = Math::BigInt->bone(); # create a +1
37 my $mone = Math::BigInt->bone('-'); # create a -1
38
39 my $pi = Math::BigInt->bpi(); # returns '3'
40 # see Math::BigFloat::bpi()
41
42 $h = Math::BigInt->new('0x123'); # from hexadecimal
43 $b = Math::BigInt->new('0b101'); # from binary
44 $o = Math::BigInt->from_oct('0101'); # from octal
45
46 # Testing (don't modify their arguments)
47 # (return true if the condition is met, otherwise false)
48
49 $x->is_zero(); # if $x is +0
50 $x->is_nan(); # if $x is NaN
51 $x->is_one(); # if $x is +1
52 $x->is_one('-'); # if $x is -1
53 $x->is_odd(); # if $x is odd
54 $x->is_even(); # if $x is even
55 $x->is_pos(); # if $x > 0
56 $x->is_neg(); # if $x < 0
57 $x->is_inf($sign); # if $x is +inf, or -inf (sign is default '+')
58 $x->is_int(); # if $x is an integer (not a float)
59
60 # comparing and digit/sign extraction
61 $x->bcmp($y); # compare numbers (undef,<0,=0,>0)
62 $x->bacmp($y); # compare absolutely (undef,<0,=0,>0)
63 $x->sign(); # return the sign, either +,- or NaN
64 $x->digit($n); # return the nth digit, counting from right
65 $x->digit(-$n); # return the nth digit, counting from left
66
67 # The following all modify their first argument. If you want to pre-
68 # serve $x, use $z = $x->copy()->bXXX($y); See under L<CAVEATS> for
69 # why this is necessary when mixing $a = $b assignments with non-over-
70 # loaded math.
71
72 $x->bzero(); # set $x to 0
73 $x->bnan(); # set $x to NaN
74 $x->bone(); # set $x to +1
75 $x->bone('-'); # set $x to -1
76 $x->binf(); # set $x to inf
77 $x->binf('-'); # set $x to -inf
78
79 $x->bneg(); # negation
80 $x->babs(); # absolute value
81 $x->bsgn(); # sign function (-1, 0, 1, or NaN)
82 $x->bnorm(); # normalize (no-op in BigInt)
83 $x->bnot(); # two's complement (bit wise not)
84 $x->binc(); # increment $x by 1
85 $x->bdec(); # decrement $x by 1
86
87 $x->badd($y); # addition (add $y to $x)
88 $x->bsub($y); # subtraction (subtract $y from $x)
89 $x->bmul($y); # multiplication (multiply $x by $y)
90 $x->bdiv($y); # divide, set $x to quotient
91 # return (quo,rem) or quo if scalar
92
93 $x->bmuladd($y,$z); # $x = $x * $y + $z
94
95 $x->bmod($y); # modulus (x % y)
96 $x->bmodpow($y,$mod); # modular exponentiation (($x ** $y) % $mod)
97 $x->bmodinv($mod); # modular multiplicative inverse
98 $x->bpow($y); # power of arguments (x ** y)
99 $x->blsft($y); # left shift in base 2
100 $x->brsft($y); # right shift in base 2
101 # returns (quo,rem) or quo if in sca-
102 # lar context
103 $x->blsft($y,$n); # left shift by $y places in base $n
104 $x->brsft($y,$n); # right shift by $y places in base $n
105 # returns (quo,rem) or quo if in sca-
106 # lar context
107
108 $x->band($y); # bitwise and
109 $x->bior($y); # bitwise inclusive or
110 $x->bxor($y); # bitwise exclusive or
111 $x->bnot(); # bitwise not (two's complement)
112
113 $x->bsqrt(); # calculate square-root
114 $x->broot($y); # $y'th root of $x (e.g. $y == 3 => cubic root)
115 $x->bfac(); # factorial of $x (1*2*3*4*..$x)
116
117 $x->bnok($y); # x over y (binomial coefficient n over k)
118
119 $x->blog(); # logarithm of $x to base e (Euler's number)
120 $x->blog($base); # logarithm of $x to base $base (f.i. 2)
121 $x->bexp(); # calculate e ** $x where e is Euler's number
122
123 $x->round($A,$P,$mode); # round to accuracy or precision using
124 # mode $mode
125 $x->bround($n); # accuracy: preserve $n digits
126 $x->bfround($n); # $n > 0: round $nth digits,
127 # $n < 0: round to the $nth digit after the
128 # dot, no-op for BigInts
129
130 # The following do not modify their arguments in BigInt (are no-ops),
131 # but do so in BigFloat:
132
133 $x->bfloor(); # return integer less or equal than $x
134 $x->bceil(); # return integer greater or equal than $x
135
136 # The following do not modify their arguments:
137
138 # greatest common divisor (no OO style)
139 my $gcd = Math::BigInt::bgcd(@values);
140 # lowest common multiple (no OO style)
141 my $lcm = Math::BigInt::blcm(@values);
142
143 $x->length(); # return number of digits in number
144 ($xl,$f) = $x->length(); # length of number and length of fraction
145 # part, latter is always 0 digits long
146 # for BigInts
147
148 $x->exponent(); # return exponent as BigInt
149 $x->mantissa(); # return (signed) mantissa as BigInt
150 $x->parts(); # return (mantissa,exponent) as BigInt
151 $x->copy(); # make a true copy of $x (unlike $y = $x;)
152 $x->as_int(); # return as BigInt (in BigInt: same as copy())
153 $x->numify(); # return as scalar (might overflow!)
154
155 # conversion to string (do not modify their argument)
156 $x->bstr(); # normalized string (e.g. '3')
157 $x->bsstr(); # norm. string in scientific notation (e.g. '3E0')
158 $x->as_hex(); # as signed hexadecimal string with prefixed 0x
159 $x->as_bin(); # as signed binary string with prefixed 0b
160 $x->as_oct(); # as signed octal string with prefixed 0
161
162
163 # precision and accuracy (see section about rounding for more)
164 $x->precision(); # return P of $x (or global, if P of $x undef)
165 $x->precision($n); # set P of $x to $n
166 $x->accuracy(); # return A of $x (or global, if A of $x undef)
167 $x->accuracy($n); # set A $x to $n
168
169 # Global methods
170 Math::BigInt->precision(); # get/set global P for all BigInt objects
171 Math::BigInt->accuracy(); # get/set global A for all BigInt objects
172 Math::BigInt->round_mode(); # get/set global round mode, one of
173 # 'even', 'odd', '+inf', '-inf', 'zero',
174 # 'trunc' or 'common'
175 Math::BigInt->config(); # return hash containing configuration
176
178 All operators (including basic math operations) are overloaded if you
179 declare your big integers as
180
181 $i = new Math::BigInt '123_456_789_123_456_789';
182
183 Operations with overloaded operators preserve the arguments which is
184 exactly what you expect.
185
186 Input
187 Input values to these routines may be any string, that looks like a
188 number and results in an integer, including hexadecimal and binary
189 numbers.
190
191 Scalars holding numbers may also be passed, but note that non-integer
192 numbers may already have lost precision due to the conversion to
193 float. Quote your input if you want BigInt to see all the digits:
194
195 $x = Math::BigInt->new(12345678890123456789); # bad
196 $x = Math::BigInt->new('12345678901234567890'); # good
197
198 You can include one underscore between any two digits.
199
200 This means integer values like 1.01E2 or even 1000E-2 are also
201 accepted. Non-integer values result in NaN.
202
203 Hexadecimal (prefixed with "0x") and binary numbers (prefixed with
204 "0b") are accepted, too. Please note that octal numbers are not
205 recognized by new(), so the following will print "123":
206
207 perl -MMath::BigInt -le 'print Math::BigInt->new("0123")'
208
209 To convert an octal number, use from_oct();
210
211 perl -MMath::BigInt -le 'print Math::BigInt->from_oct("0123")'
212
213 Currently, Math::BigInt::new() defaults to 0, while
214 Math::BigInt::new('') results in 'NaN'. This might change in the
215 future, so use always the following explicit forms to get a zero or
216 NaN:
217
218 $zero = Math::BigInt->bzero();
219 $nan = Math::BigInt->bnan();
220
221 "bnorm()" on a BigInt object is now effectively a no-op, since the
222 numbers are always stored in normalized form. If passed a string,
223 creates a BigInt object from the input.
224
225 Output
226 Output values are BigInt objects (normalized), except for the methods
227 which return a string (see "SYNOPSIS").
228
229 Some routines ("is_odd()", "is_even()", "is_zero()", "is_one()",
230 "is_nan()", etc.) return true or false, while others ("bcmp()",
231 "bacmp()") return either undef (if NaN is involved), <0, 0 or >0 and
232 are suited for sort.
233
235 Each of the methods below (except config(), accuracy() and precision())
236 accepts three additional parameters. These arguments $A, $P and $R are
237 "accuracy", "precision" and "round_mode". Please see the section about
238 "ACCURACY and PRECISION" for more information.
239
240 config()
241 use Data::Dumper;
242
243 print Dumper ( Math::BigInt->config() );
244 print Math::BigInt->config()->{lib},"\n";
245
246 Returns a hash containing the configuration, e.g. the version number,
247 lib loaded etc. The following hash keys are currently filled in with
248 the appropriate information.
249
250 key Description
251 Example
252 ============================================================
253 lib Name of the low-level math library
254 Math::BigInt::Calc
255 lib_version Version of low-level math library (see 'lib')
256 0.30
257 class The class name of config() you just called
258 Math::BigInt
259 upgrade To which class math operations might be upgraded
260 Math::BigFloat
261 downgrade To which class math operations might be downgraded
262 undef
263 precision Global precision
264 undef
265 accuracy Global accuracy
266 undef
267 round_mode Global round mode
268 even
269 version version number of the class you used
270 1.61
271 div_scale Fallback accuracy for div
272 40
273 trap_nan If true, traps creation of NaN via croak()
274 1
275 trap_inf If true, traps creation of +inf/-inf via croak()
276 1
277
278 The following values can be set by passing "config()" a reference to a
279 hash:
280
281 trap_inf trap_nan
282 upgrade downgrade precision accuracy round_mode div_scale
283
284 Example:
285
286 $new_cfg = Math::BigInt->config(
287 { trap_inf => 1, precision => 5 }
288 );
289
290 accuracy()
291 $x->accuracy(5); # local for $x
292 CLASS->accuracy(5); # global for all members of CLASS
293 # Note: This also applies to new()!
294
295 $A = $x->accuracy(); # read out accuracy that affects $x
296 $A = CLASS->accuracy(); # read out global accuracy
297
298 Set or get the global or local accuracy, aka how many significant
299 digits the results have. If you set a global accuracy, then this also
300 applies to new()!
301
302 Warning! The accuracy sticks, e.g. once you created a number under the
303 influence of "CLASS->accuracy($A)", all results from math operations
304 with that number will also be rounded.
305
306 In most cases, you should probably round the results explicitly using
307 one of "round()", "bround()" or "bfround()" or by passing the desired
308 accuracy to the math operation as additional parameter:
309
310 my $x = Math::BigInt->new(30000);
311 my $y = Math::BigInt->new(7);
312 print scalar $x->copy()->bdiv($y, 2); # print 4300
313 print scalar $x->copy()->bdiv($y)->bround(2); # print 4300
314
315 Please see the section about "ACCURACY and PRECISION" for further
316 details.
317
318 Value must be greater than zero. Pass an undef value to disable it:
319
320 $x->accuracy(undef);
321 Math::BigInt->accuracy(undef);
322
323 Returns the current accuracy. For "$x->accuracy()" it will return
324 either the local accuracy, or if not defined, the global. This means
325 the return value represents the accuracy that will be in effect for $x:
326
327 $y = Math::BigInt->new(1234567); # unrounded
328 print Math::BigInt->accuracy(4),"\n"; # set 4, print 4
329 $x = Math::BigInt->new(123456); # $x will be automatic-
330 # ally rounded!
331 print "$x $y\n"; # '123500 1234567'
332 print $x->accuracy(),"\n"; # will be 4
333 print $y->accuracy(),"\n"; # also 4, since global is 4
334 print Math::BigInt->accuracy(5),"\n"; # set to 5, print 5
335 print $x->accuracy(),"\n"; # still 4
336 print $y->accuracy(),"\n"; # 5, since global is 5
337
338 Note: Works also for subclasses like Math::BigFloat. Each class has
339 it's own globals separated from Math::BigInt, but it is possible to
340 subclass Math::BigInt and make the globals of the subclass aliases to
341 the ones from Math::BigInt.
342
343 precision()
344 $x->precision(-2); # local for $x, round at the second
345 # digit right of the dot
346 $x->precision(2); # ditto, round at the second digit left
347 # of the dot
348
349 CLASS->precision(5); # Global for all members of CLASS
350 # This also applies to new()!
351 CLASS->precision(-5); # ditto
352
353 $P = CLASS->precision(); # read out global precision
354 $P = $x->precision(); # read out precision that affects $x
355
356 Note: You probably want to use "accuracy()" instead. With "accuracy()"
357 you set the number of digits each result should have, with
358 "precision()" you set the place where to round!
359
360 "precision()" sets or gets the global or local precision, aka at which
361 digit before or after the dot to round all results. A set global
362 precision also applies to all newly created numbers!
363
364 In Math::BigInt, passing a negative number precision has no effect
365 since no numbers have digits after the dot. In Math::BigFloat, it will
366 round all results to P digits after the dot.
367
368 Please see the section about "ACCURACY and PRECISION" for further
369 details.
370
371 Pass an undef value to disable it:
372
373 $x->precision(undef);
374 Math::BigInt->precision(undef);
375
376 Returns the current precision. For "$x->precision()" it will return
377 either the local precision of $x, or if not defined, the global. This
378 means the return value represents the prevision that will be in effect
379 for $x:
380
381 $y = Math::BigInt->new(1234567); # unrounded
382 print Math::BigInt->precision(4),"\n"; # set 4, print 4
383 $x = Math::BigInt->new(123456); # will be automatically rounded
384 print $x; # print "120000"!
385
386 Note: Works also for subclasses like Math::BigFloat. Each class has its
387 own globals separated from Math::BigInt, but it is possible to subclass
388 Math::BigInt and make the globals of the subclass aliases to the ones
389 from Math::BigInt.
390
391 brsft()
392 $x->brsft($y,$n);
393
394 Shifts $x right by $y in base $n. Default is base 2, used are usually
395 10 and 2, but others work, too.
396
397 Right shifting usually amounts to dividing $x by $n ** $y and
398 truncating the result:
399
400 $x = Math::BigInt->new(10);
401 $x->brsft(1); # same as $x >> 1: 5
402 $x = Math::BigInt->new(1234);
403 $x->brsft(2,10); # result 12
404
405 There is one exception, and that is base 2 with negative $x:
406
407 $x = Math::BigInt->new(-5);
408 print $x->brsft(1);
409
410 This will print -3, not -2 (as it would if you divide -5 by 2 and
411 truncate the result).
412
413 new()
414 $x = Math::BigInt->new($str,$A,$P,$R);
415
416 Creates a new BigInt object from a scalar or another BigInt object. The
417 input is accepted as decimal, hex (with leading '0x') or binary (with
418 leading '0b').
419
420 See "Input" for more info on accepted input formats.
421
422 from_oct()
423 $x = Math::BigInt->from_oct("0775"); # input is octal
424
425 Interpret the input as an octal string and return the corresponding
426 value. A "0" (zero) prefix is optional. A single underscore character
427 may be placed right after the prefix, if present, or between any two
428 digits. If the input is invalid, a NaN is returned.
429
430 from_hex()
431 $x = Math::BigInt->from_hex("0xcafe"); # input is hexadecimal
432
433 Interpret input as a hexadecimal string. A "0x" or "x" prefix is
434 optional. A single underscore character may be placed right after the
435 prefix, if present, or between any two digits. If the input is invalid,
436 a NaN is returned.
437
438 from_bin()
439 $x = Math::BigInt->from_bin("0b10011"); # input is binary
440
441 Interpret the input as a binary string. A "0b" or "b" prefix is
442 optional. A single underscore character may be placed right after the
443 prefix, if present, or between any two digits. If the input is invalid,
444 a NaN is returned.
445
446 bnan()
447 $x = Math::BigInt->bnan();
448
449 Creates a new BigInt object representing NaN (Not A Number). If used
450 on an object, it will set it to NaN:
451
452 $x->bnan();
453
454 bzero()
455 $x = Math::BigInt->bzero();
456
457 Creates a new BigInt object representing zero. If used on an object,
458 it will set it to zero:
459
460 $x->bzero();
461
462 binf()
463 $x = Math::BigInt->binf($sign);
464
465 Creates a new BigInt object representing infinity. The optional
466 argument is either '-' or '+', indicating whether you want infinity or
467 minus infinity. If used on an object, it will set it to infinity:
468
469 $x->binf();
470 $x->binf('-');
471
472 bone()
473 $x = Math::BigInt->binf($sign);
474
475 Creates a new BigInt object representing one. The optional argument is
476 either '-' or '+', indicating whether you want one or minus one. If
477 used on an object, it will set it to one:
478
479 $x->bone(); # +1
480 $x->bone('-'); # -1
481
482 is_one()/is_zero()/is_nan()/is_inf()
483 $x->is_zero(); # true if arg is +0
484 $x->is_nan(); # true if arg is NaN
485 $x->is_one(); # true if arg is +1
486 $x->is_one('-'); # true if arg is -1
487 $x->is_inf(); # true if +inf
488 $x->is_inf('-'); # true if -inf (sign is default '+')
489
490 These methods all test the BigInt for being one specific value and
491 return true or false depending on the input. These are faster than
492 doing something like:
493
494 if ($x == 0)
495
496 is_pos()/is_neg()/is_positive()/is_negative()
497 $x->is_pos(); # true if > 0
498 $x->is_neg(); # true if < 0
499
500 The methods return true if the argument is positive or negative,
501 respectively. "NaN" is neither positive nor negative, while "+inf"
502 counts as positive, and "-inf" is negative. A "zero" is neither
503 positive nor negative.
504
505 These methods are only testing the sign, and not the value.
506
507 "is_positive()" and "is_negative()" are aliases to "is_pos()" and
508 "is_neg()", respectively. "is_positive()" and "is_negative()" were
509 introduced in v1.36, while "is_pos()" and "is_neg()" were only
510 introduced in v1.68.
511
512 is_odd()/is_even()/is_int()
513 $x->is_odd(); # true if odd, false for even
514 $x->is_even(); # true if even, false for odd
515 $x->is_int(); # true if $x is an integer
516
517 The return true when the argument satisfies the condition. "NaN",
518 "+inf", "-inf" are not integers and are neither odd nor even.
519
520 In BigInt, all numbers except "NaN", "+inf" and "-inf" are integers.
521
522 bcmp()
523 $x->bcmp($y);
524
525 Compares $x with $y and takes the sign into account. Returns -1, 0, 1
526 or undef.
527
528 bacmp()
529 $x->bacmp($y);
530
531 Compares $x with $y while ignoring their sign. Returns -1, 0, 1 or
532 undef.
533
534 sign()
535 $x->sign();
536
537 Return the sign, of $x, meaning either "+", "-", "-inf", "+inf" or NaN.
538
539 If you want $x to have a certain sign, use one of the following
540 methods:
541
542 $x->babs(); # '+'
543 $x->babs()->bneg(); # '-'
544 $x->bnan(); # 'NaN'
545 $x->binf(); # '+inf'
546 $x->binf('-'); # '-inf'
547
548 digit()
549 $x->digit($n); # return the nth digit, counting from right
550
551 If $n is negative, returns the digit counting from left.
552
553 bneg()
554 $x->bneg();
555
556 Negate the number, e.g. change the sign between '+' and '-', or between
557 '+inf' and '-inf', respectively. Does nothing for NaN or zero.
558
559 babs()
560 $x->babs();
561
562 Set the number to its absolute value, e.g. change the sign from '-' to
563 '+' and from '-inf' to '+inf', respectively. Does nothing for NaN or
564 positive numbers.
565
566 bsgn()
567 $x->bsgn();
568
569 Signum function. Set the number to -1, 0, or 1, depending on whether
570 the number is negative, zero, or positive, respectivly. Does not modify
571 NaNs.
572
573 bnorm()
574 $x->bnorm(); # normalize (no-op)
575
576 bnot()
577 $x->bnot();
578
579 Two's complement (bitwise not). This is equivalent to
580
581 $x->binc()->bneg();
582
583 but faster.
584
585 binc()
586 $x->binc(); # increment x by 1
587
588 bdec()
589 $x->bdec(); # decrement x by 1
590
591 badd()
592 $x->badd($y); # addition (add $y to $x)
593
594 bsub()
595 $x->bsub($y); # subtraction (subtract $y from $x)
596
597 bmul()
598 $x->bmul($y); # multiplication (multiply $x by $y)
599
600 bmuladd()
601 $x->bmuladd($y,$z);
602
603 Multiply $x by $y, and then add $z to the result,
604
605 This method was added in v1.87 of Math::BigInt (June 2007).
606
607 bdiv()
608 $x->bdiv($y); # divide, set $x to quotient
609 # return (quo,rem) or quo if scalar
610
611 bmod()
612 $x->bmod($y); # modulus (x % y)
613
614 bmodinv()
615 $x->bmodinv($mod); # modular multiplicative inverse
616
617 Returns the multiplicative inverse of $x modulo $mod. If
618
619 $y = $x -> copy() -> bmodinv($mod)
620
621 then $y is the number closest to zero, and with the same sign as $mod,
622 satisfying
623
624 ($x * $y) % $mod = 1 % $mod
625
626 If $x and $y are non-zero, they must be relative primes, i.e.,
627 "bgcd($y, $mod)==1". '"NaN"' is returned when no modular multiplicative
628 inverse exists.
629
630 bmodpow()
631 $num->bmodpow($exp,$mod); # modular exponentiation
632 # ($num**$exp % $mod)
633
634 Returns the value of $num taken to the power $exp in the modulus $mod
635 using binary exponentiation. "bmodpow" is far superior to writing
636
637 $num ** $exp % $mod
638
639 because it is much faster - it reduces internal variables into the
640 modulus whenever possible, so it operates on smaller numbers.
641
642 "bmodpow" also supports negative exponents.
643
644 bmodpow($num, -1, $mod)
645
646 is exactly equivalent to
647
648 bmodinv($num, $mod)
649
650 bpow()
651 $x->bpow($y); # power of arguments (x ** y)
652
653 blog()
654 $x->blog($base, $accuracy); # logarithm of x to the base $base
655
656 If $base is not defined, Euler's number (e) is used:
657
658 print $x->blog(undef, 100); # log(x) to 100 digits
659
660 bexp()
661 $x->bexp($accuracy); # calculate e ** X
662
663 Calculates the expression "e ** $x" where "e" is Euler's number.
664
665 This method was added in v1.82 of Math::BigInt (April 2007).
666
667 See also "blog()".
668
669 bnok()
670 $x->bnok($y); # x over y (binomial coefficient n over k)
671
672 Calculates the binomial coefficient n over k, also called the "choose"
673 function. The result is equivalent to:
674
675 ( n ) n!
676 | - | = -------
677 ( k ) k!(n-k)!
678
679 This method was added in v1.84 of Math::BigInt (April 2007).
680
681 bpi()
682 print Math::BigInt->bpi(100), "\n"; # 3
683
684 Returns PI truncated to an integer, with the argument being ignored.
685 This means under BigInt this always returns 3.
686
687 If upgrading is in effect, returns PI, rounded to N digits with the
688 current rounding mode:
689
690 use Math::BigFloat;
691 use Math::BigInt upgrade => Math::BigFloat;
692 print Math::BigInt->bpi(3), "\n"; # 3.14
693 print Math::BigInt->bpi(100), "\n"; # 3.1415....
694
695 This method was added in v1.87 of Math::BigInt (June 2007).
696
697 bcos()
698 my $x = Math::BigInt->new(1);
699 print $x->bcos(100), "\n";
700
701 Calculate the cosinus of $x, modifying $x in place.
702
703 In BigInt, unless upgrading is in effect, the result is truncated to an
704 integer.
705
706 This method was added in v1.87 of Math::BigInt (June 2007).
707
708 bsin()
709 my $x = Math::BigInt->new(1);
710 print $x->bsin(100), "\n";
711
712 Calculate the sinus of $x, modifying $x in place.
713
714 In BigInt, unless upgrading is in effect, the result is truncated to an
715 integer.
716
717 This method was added in v1.87 of Math::BigInt (June 2007).
718
719 batan2()
720 my $x = Math::BigInt->new(1);
721 my $y = Math::BigInt->new(1);
722 print $y->batan2($x), "\n";
723
724 Calculate the arcus tangens of $y divided by $x, modifying $y in place.
725
726 In BigInt, unless upgrading is in effect, the result is truncated to an
727 integer.
728
729 This method was added in v1.87 of Math::BigInt (June 2007).
730
731 batan()
732 my $x = Math::BigFloat->new(0.5);
733 print $x->batan(100), "\n";
734
735 Calculate the arcus tangens of $x, modifying $x in place.
736
737 In BigInt, unless upgrading is in effect, the result is truncated to an
738 integer.
739
740 This method was added in v1.87 of Math::BigInt (June 2007).
741
742 blsft()
743 $x->blsft($y); # left shift in base 2
744 $x->blsft($y,$n); # left shift, in base $n (like 10)
745
746 brsft()
747 $x->brsft($y); # right shift in base 2
748 $x->brsft($y,$n); # right shift, in base $n (like 10)
749
750 band()
751 $x->band($y); # bitwise and
752
753 bior()
754 $x->bior($y); # bitwise inclusive or
755
756 bxor()
757 $x->bxor($y); # bitwise exclusive or
758
759 bnot()
760 $x->bnot(); # bitwise not (two's complement)
761
762 bsqrt()
763 $x->bsqrt(); # calculate square-root
764
765 broot()
766 $x->broot($N);
767
768 Calculates the N'th root of $x.
769
770 bfac()
771 $x->bfac(); # factorial of $x (1*2*3*4*..$x)
772
773 round()
774 $x->round($A,$P,$round_mode);
775
776 Round $x to accuracy $A or precision $P using the round mode
777 $round_mode.
778
779 bround()
780 $x->bround($N); # accuracy: preserve $N digits
781
782 bfround()
783 $x->bfround($N);
784
785 If N is > 0, rounds to the Nth digit from the left. If N < 0, rounds to
786 the Nth digit after the dot. Since BigInts are integers, the case N < 0
787 is a no-op for them.
788
789 Examples:
790
791 Input N Result
792 ===================================================
793 123456.123456 3 123500
794 123456.123456 2 123450
795 123456.123456 -2 123456.12
796 123456.123456 -3 123456.123
797
798 bfloor()
799 $x->bfloor();
800
801 Set $x to the integer less or equal than $x. This is a no-op in BigInt,
802 but does change $x in BigFloat.
803
804 bceil()
805 $x->bceil();
806
807 Set $x to the integer greater or equal than $x. This is a no-op in
808 BigInt, but does change $x in BigFloat.
809
810 bgcd()
811 bgcd(@values); # greatest common divisor (no OO style)
812
813 blcm()
814 blcm(@values); # lowest common multiple (no OO style)
815
816 head2 length()
817
818 $x->length();
819 ($xl,$fl) = $x->length();
820
821 Returns the number of digits in the decimal representation of the
822 number. In list context, returns the length of the integer and
823 fraction part. For BigInt's, the length of the fraction part will
824 always be 0.
825
826 exponent()
827 $x->exponent();
828
829 Return the exponent of $x as BigInt.
830
831 mantissa()
832 $x->mantissa();
833
834 Return the signed mantissa of $x as BigInt.
835
836 parts()
837 $x->parts(); # return (mantissa,exponent) as BigInt
838
839 copy()
840 $x->copy(); # make a true copy of $x (unlike $y = $x;)
841
842 as_int()/as_number()
843 $x->as_int();
844
845 Returns $x as a BigInt (truncated towards zero). In BigInt this is the
846 same as "copy()".
847
848 "as_number()" is an alias to this method. "as_number" was introduced in
849 v1.22, while "as_int()" was only introduced in v1.68.
850
851 bstr()
852 $x->bstr();
853
854 Returns a normalized string representation of $x.
855
856 bsstr()
857 $x->bsstr(); # normalized string in scientific notation
858
859 as_hex()
860 $x->as_hex(); # as signed hexadecimal string with prefixed 0x
861
862 as_bin()
863 $x->as_bin(); # as signed binary string with prefixed 0b
864
865 as_oct()
866 $x->as_oct(); # as signed octal string with prefixed 0
867
868 numify()
869 print $x->numify();
870
871 This returns a normal Perl scalar from $x. It is used automatically
872 whenever a scalar is needed, for instance in array index operations.
873
874 This loses precision, to avoid this use as_int() instead.
875
876 modify()
877 $x->modify('bpowd');
878
879 This method returns 0 if the object can be modified with the given
880 operation, or 1 if not.
881
882 This is used for instance by Math::BigInt::Constant.
883
884 upgrade()/downgrade()
885 Set/get the class for downgrade/upgrade operations. Thuis is used for
886 instance by bignum. The defaults are '', thus the following operation
887 will create a BigInt, not a BigFloat:
888
889 my $i = Math::BigInt->new(123);
890 my $f = Math::BigFloat->new('123.1');
891
892 print $i + $f,"\n"; # print 246
893
894 div_scale()
895 Set/get the number of digits for the default precision in divide
896 operations.
897
898 round_mode()
899 Set/get the current round mode.
900
902 Since version v1.33, Math::BigInt and Math::BigFloat have full support
903 for accuracy and precision based rounding, both automatically after
904 every operation, as well as manually.
905
906 This section describes the accuracy/precision handling in Math::Big* as
907 it used to be and as it is now, complete with an explanation of all
908 terms and abbreviations.
909
910 Not yet implemented things (but with correct description) are marked
911 with '!', things that need to be answered are marked with '?'.
912
913 In the next paragraph follows a short description of terms used here
914 (because these may differ from terms used by others people or
915 documentation).
916
917 During the rest of this document, the shortcuts A (for accuracy), P
918 (for precision), F (fallback) and R (rounding mode) will be used.
919
920 Precision P
921 A fixed number of digits before (positive) or after (negative) the
922 decimal point. For example, 123.45 has a precision of -2. 0 means an
923 integer like 123 (or 120). A precision of 2 means two digits to the
924 left of the decimal point are zero, so 123 with P = 1 becomes 120. Note
925 that numbers with zeros before the decimal point may have different
926 precisions, because 1200 can have p = 0, 1 or 2 (depending on what the
927 initial value was). It could also have p < 0, when the digits after the
928 decimal point are zero.
929
930 The string output (of floating point numbers) will be padded with
931 zeros:
932
933 Initial value P A Result String
934 ------------------------------------------------------------
935 1234.01 -3 1000 1000
936 1234 -2 1200 1200
937 1234.5 -1 1230 1230
938 1234.001 1 1234 1234.0
939 1234.01 0 1234 1234
940 1234.01 2 1234.01 1234.01
941 1234.01 5 1234.01 1234.01000
942
943 For BigInts, no padding occurs.
944
945 Accuracy A
946 Number of significant digits. Leading zeros are not counted. A number
947 may have an accuracy greater than the non-zero digits when there are
948 zeros in it or trailing zeros. For example, 123.456 has A of 6, 10203
949 has 5, 123.0506 has 7, 123.450000 has 8 and 0.000123 has 3.
950
951 The string output (of floating point numbers) will be padded with
952 zeros:
953
954 Initial value P A Result String
955 ------------------------------------------------------------
956 1234.01 3 1230 1230
957 1234.01 6 1234.01 1234.01
958 1234.1 8 1234.1 1234.1000
959
960 For BigInts, no padding occurs.
961
962 Fallback F
963 When both A and P are undefined, this is used as a fallback accuracy
964 when dividing numbers.
965
966 Rounding mode R
967 When rounding a number, different 'styles' or 'kinds' of rounding are
968 possible. (Note that random rounding, as in Math::Round, is not
969 implemented.)
970
971 'trunc'
972 truncation invariably removes all digits following the rounding
973 place, replacing them with zeros. Thus, 987.65 rounded to tens (P=1)
974 becomes 980, and rounded to the fourth sigdig becomes 987.6 (A=4).
975 123.456 rounded to the second place after the decimal point (P=-2)
976 becomes 123.46.
977
978 All other implemented styles of rounding attempt to round to the
979 "nearest digit." If the digit D immediately to the right of the
980 rounding place (skipping the decimal point) is greater than 5, the
981 number is incremented at the rounding place (possibly causing a
982 cascade of incrementation): e.g. when rounding to units, 0.9 rounds
983 to 1, and -19.9 rounds to -20. If D < 5, the number is similarly
984 truncated at the rounding place: e.g. when rounding to units, 0.4
985 rounds to 0, and -19.4 rounds to -19.
986
987 However the results of other styles of rounding differ if the digit
988 immediately to the right of the rounding place (skipping the decimal
989 point) is 5 and if there are no digits, or no digits other than 0,
990 after that 5. In such cases:
991
992 'even'
993 rounds the digit at the rounding place to 0, 2, 4, 6, or 8 if it is
994 not already. E.g., when rounding to the first sigdig, 0.45 becomes
995 0.4, -0.55 becomes -0.6, but 0.4501 becomes 0.5.
996
997 'odd'
998 rounds the digit at the rounding place to 1, 3, 5, 7, or 9 if it is
999 not already. E.g., when rounding to the first sigdig, 0.45 becomes
1000 0.5, -0.55 becomes -0.5, but 0.5501 becomes 0.6.
1001
1002 '+inf'
1003 round to plus infinity, i.e. always round up. E.g., when rounding to
1004 the first sigdig, 0.45 becomes 0.5, -0.55 becomes -0.5, and 0.4501
1005 also becomes 0.5.
1006
1007 '-inf'
1008 round to minus infinity, i.e. always round down. E.g., when rounding
1009 to the first sigdig, 0.45 becomes 0.4, -0.55 becomes -0.6, but 0.4501
1010 becomes 0.5.
1011
1012 'zero'
1013 round to zero, i.e. positive numbers down, negative ones up. E.g.,
1014 when rounding to the first sigdig, 0.45 becomes 0.4, -0.55 becomes
1015 -0.5, but 0.4501 becomes 0.5.
1016
1017 'common'
1018 round up if the digit immediately to the right of the rounding place
1019 is 5 or greater, otherwise round down. E.g., 0.15 becomes 0.2 and
1020 0.149 becomes 0.1.
1021
1022 The handling of A & P in MBI/MBF (the old core code shipped with Perl
1023 versions <= 5.7.2) is like this:
1024
1025 Precision
1026 * ffround($p) is able to round to $p number of digits after the decimal
1027 point
1028 * otherwise P is unused
1029
1030 Accuracy (significant digits)
1031 * fround($a) rounds to $a significant digits
1032 * only fdiv() and fsqrt() take A as (optional) parameter
1033 + other operations simply create the same number (fneg etc), or more (fmul)
1034 of digits
1035 + rounding/truncating is only done when explicitly calling one of fround
1036 or ffround, and never for BigInt (not implemented)
1037 * fsqrt() simply hands its accuracy argument over to fdiv.
1038 * the documentation and the comment in the code indicate two different ways
1039 on how fdiv() determines the maximum number of digits it should calculate,
1040 and the actual code does yet another thing
1041 POD:
1042 max($Math::BigFloat::div_scale,length(dividend)+length(divisor))
1043 Comment:
1044 result has at most max(scale, length(dividend), length(divisor)) digits
1045 Actual code:
1046 scale = max(scale, length(dividend)-1,length(divisor)-1);
1047 scale += length(divisor) - length(dividend);
1048 So for lx = 3, ly = 9, scale = 10, scale will actually be 16 (10+9-3).
1049 Actually, the 'difference' added to the scale is calculated from the
1050 number of "significant digits" in dividend and divisor, which is derived
1051 by looking at the length of the mantissa. Which is wrong, since it includes
1052 the + sign (oops) and actually gets 2 for '+100' and 4 for '+101'. Oops
1053 again. Thus 124/3 with div_scale=1 will get you '41.3' based on the strange
1054 assumption that 124 has 3 significant digits, while 120/7 will get you
1055 '17', not '17.1' since 120 is thought to have 2 significant digits.
1056 The rounding after the division then uses the remainder and $y to determine
1057 whether it must round up or down.
1058 ? I have no idea which is the right way. That's why I used a slightly more
1059 ? simple scheme and tweaked the few failing testcases to match it.
1060
1061 This is how it works now:
1062
1063 Setting/Accessing
1064 * You can set the A global via Math::BigInt->accuracy() or
1065 Math::BigFloat->accuracy() or whatever class you are using.
1066 * You can also set P globally by using Math::SomeClass->precision()
1067 likewise.
1068 * Globals are classwide, and not inherited by subclasses.
1069 * to undefine A, use Math::SomeCLass->accuracy(undef);
1070 * to undefine P, use Math::SomeClass->precision(undef);
1071 * Setting Math::SomeClass->accuracy() clears automatically
1072 Math::SomeClass->precision(), and vice versa.
1073 * To be valid, A must be > 0, P can have any value.
1074 * If P is negative, this means round to the P'th place to the right of the
1075 decimal point; positive values mean to the left of the decimal point.
1076 P of 0 means round to integer.
1077 * to find out the current global A, use Math::SomeClass->accuracy()
1078 * to find out the current global P, use Math::SomeClass->precision()
1079 * use $x->accuracy() respective $x->precision() for the local
1080 setting of $x.
1081 * Please note that $x->accuracy() respective $x->precision()
1082 return eventually defined global A or P, when $x's A or P is not
1083 set.
1084
1085 Creating numbers
1086 * When you create a number, you can give the desired A or P via:
1087 $x = Math::BigInt->new($number,$A,$P);
1088 * Only one of A or P can be defined, otherwise the result is NaN
1089 * If no A or P is give ($x = Math::BigInt->new($number) form), then the
1090 globals (if set) will be used. Thus changing the global defaults later on
1091 will not change the A or P of previously created numbers (i.e., A and P of
1092 $x will be what was in effect when $x was created)
1093 * If given undef for A and P, NO rounding will occur, and the globals will
1094 NOT be used. This is used by subclasses to create numbers without
1095 suffering rounding in the parent. Thus a subclass is able to have its own
1096 globals enforced upon creation of a number by using
1097 $x = Math::BigInt->new($number,undef,undef):
1098
1099 use Math::BigInt::SomeSubclass;
1100 use Math::BigInt;
1101
1102 Math::BigInt->accuracy(2);
1103 Math::BigInt::SomeSubClass->accuracy(3);
1104 $x = Math::BigInt::SomeSubClass->new(1234);
1105
1106 $x is now 1230, and not 1200. A subclass might choose to implement
1107 this otherwise, e.g. falling back to the parent's A and P.
1108
1109 Usage
1110 * If A or P are enabled/defined, they are used to round the result of each
1111 operation according to the rules below
1112 * Negative P is ignored in Math::BigInt, since BigInts never have digits
1113 after the decimal point
1114 * Math::BigFloat uses Math::BigInt internally, but setting A or P inside
1115 Math::BigInt as globals does not tamper with the parts of a BigFloat.
1116 A flag is used to mark all Math::BigFloat numbers as 'never round'.
1117
1118 Precedence
1119 * It only makes sense that a number has only one of A or P at a time.
1120 If you set either A or P on one object, or globally, the other one will
1121 be automatically cleared.
1122 * If two objects are involved in an operation, and one of them has A in
1123 effect, and the other P, this results in an error (NaN).
1124 * A takes precedence over P (Hint: A comes before P).
1125 If neither of them is defined, nothing is used, i.e. the result will have
1126 as many digits as it can (with an exception for fdiv/fsqrt) and will not
1127 be rounded.
1128 * There is another setting for fdiv() (and thus for fsqrt()). If neither of
1129 A or P is defined, fdiv() will use a fallback (F) of $div_scale digits.
1130 If either the dividend's or the divisor's mantissa has more digits than
1131 the value of F, the higher value will be used instead of F.
1132 This is to limit the digits (A) of the result (just consider what would
1133 happen with unlimited A and P in the case of 1/3 :-)
1134 * fdiv will calculate (at least) 4 more digits than required (determined by
1135 A, P or F), and, if F is not used, round the result
1136 (this will still fail in the case of a result like 0.12345000000001 with A
1137 or P of 5, but this can not be helped - or can it?)
1138 * Thus you can have the math done by on Math::Big* class in two modi:
1139 + never round (this is the default):
1140 This is done by setting A and P to undef. No math operation
1141 will round the result, with fdiv() and fsqrt() as exceptions to guard
1142 against overflows. You must explicitly call bround(), bfround() or
1143 round() (the latter with parameters).
1144 Note: Once you have rounded a number, the settings will 'stick' on it
1145 and 'infect' all other numbers engaged in math operations with it, since
1146 local settings have the highest precedence. So, to get SaferRound[tm],
1147 use a copy() before rounding like this:
1148
1149 $x = Math::BigFloat->new(12.34);
1150 $y = Math::BigFloat->new(98.76);
1151 $z = $x * $y; # 1218.6984
1152 print $x->copy()->fround(3); # 12.3 (but A is now 3!)
1153 $z = $x * $y; # still 1218.6984, without
1154 # copy would have been 1210!
1155
1156 + round after each op:
1157 After each single operation (except for testing like is_zero()), the
1158 method round() is called and the result is rounded appropriately. By
1159 setting proper values for A and P, you can have all-the-same-A or
1160 all-the-same-P modes. For example, Math::Currency might set A to undef,
1161 and P to -2, globally.
1162
1163 ?Maybe an extra option that forbids local A & P settings would be in order,
1164 ?so that intermediate rounding does not 'poison' further math?
1165
1166 Overriding globals
1167 * you will be able to give A, P and R as an argument to all the calculation
1168 routines; the second parameter is A, the third one is P, and the fourth is
1169 R (shift right by one for binary operations like badd). P is used only if
1170 the first parameter (A) is undefined. These three parameters override the
1171 globals in the order detailed as follows, i.e. the first defined value
1172 wins:
1173 (local: per object, global: global default, parameter: argument to sub)
1174 + parameter A
1175 + parameter P
1176 + local A (if defined on both of the operands: smaller one is taken)
1177 + local P (if defined on both of the operands: bigger one is taken)
1178 + global A
1179 + global P
1180 + global F
1181 * fsqrt() will hand its arguments to fdiv(), as it used to, only now for two
1182 arguments (A and P) instead of one
1183
1184 Local settings
1185 * You can set A or P locally by using $x->accuracy() or
1186 $x->precision()
1187 and thus force different A and P for different objects/numbers.
1188 * Setting A or P this way immediately rounds $x to the new value.
1189 * $x->accuracy() clears $x->precision(), and vice versa.
1190
1191 Rounding
1192 * the rounding routines will use the respective global or local settings.
1193 fround()/bround() is for accuracy rounding, while ffround()/bfround()
1194 is for precision
1195 * the two rounding functions take as the second parameter one of the
1196 following rounding modes (R):
1197 'even', 'odd', '+inf', '-inf', 'zero', 'trunc', 'common'
1198 * you can set/get the global R by using Math::SomeClass->round_mode()
1199 or by setting $Math::SomeClass::round_mode
1200 * after each operation, $result->round() is called, and the result may
1201 eventually be rounded (that is, if A or P were set either locally,
1202 globally or as parameter to the operation)
1203 * to manually round a number, call $x->round($A,$P,$round_mode);
1204 this will round the number by using the appropriate rounding function
1205 and then normalize it.
1206 * rounding modifies the local settings of the number:
1207
1208 $x = Math::BigFloat->new(123.456);
1209 $x->accuracy(5);
1210 $x->bround(4);
1211
1212 Here 4 takes precedence over 5, so 123.5 is the result and $x->accuracy()
1213 will be 4 from now on.
1214
1215 Default values
1216 * R: 'even'
1217 * F: 40
1218 * A: undef
1219 * P: undef
1220
1221 Remarks
1222 * The defaults are set up so that the new code gives the same results as
1223 the old code (except in a few cases on fdiv):
1224 + Both A and P are undefined and thus will not be used for rounding
1225 after each operation.
1226 + round() is thus a no-op, unless given extra parameters A and P
1227
1229 While BigInt has extensive handling of inf and NaN, certain quirks
1230 remain.
1231
1232 oct()/hex()
1233 These perl routines currently (as of Perl v.5.8.6) cannot handle
1234 passed inf.
1235
1236 te@linux:~> perl -wle 'print 2 ** 3333'
1237 inf
1238 te@linux:~> perl -wle 'print 2 ** 3333 == 2 ** 3333'
1239 1
1240 te@linux:~> perl -wle 'print oct(2 ** 3333)'
1241 0
1242 te@linux:~> perl -wle 'print hex(2 ** 3333)'
1243 Illegal hexadecimal digit 'i' ignored at -e line 1.
1244 0
1245
1246 The same problems occur if you pass them Math::BigInt->binf()
1247 objects. Since overloading these routines is not possible, this
1248 cannot be fixed from BigInt.
1249
1250 ==, !=, <, >, <=, >= with NaNs
1251 BigInt's bcmp() routine currently returns undef to signal that a NaN
1252 was involved in a comparison. However, the overload code turns that
1253 into either 1 or '' and thus operations like "NaN != NaN" might
1254 return wrong values.
1255
1256 log(-inf)
1257 "log(-inf)" is highly weird. Since log(-x)=pi*i+log(x), then
1258 log(-inf)=pi*i+inf. However, since the imaginary part is finite, the
1259 real infinity "overshadows" it, so the number might as well just be
1260 infinity. However, the result is a complex number, and since
1261 BigInt/BigFloat can only have real numbers as results, the result is
1262 NaN.
1263
1264 exp(), cos(), sin(), atan2()
1265 These all might have problems handling infinity right.
1266
1268 The actual numbers are stored as unsigned big integers (with separate
1269 sign).
1270
1271 You should neither care about nor depend on the internal
1272 representation; it might change without notice. Use ONLY method calls
1273 like "$x->sign();" instead relying on the internal representation.
1274
1275 MATH LIBRARY
1276 Math with the numbers is done (by default) by a module called
1277 "Math::BigInt::Calc". This is equivalent to saying:
1278
1279 use Math::BigInt try => 'Calc';
1280
1281 You can change this backend library by using:
1282
1283 use Math::BigInt try => 'GMP';
1284
1285 Note: General purpose packages should not be explicit about the library
1286 to use; let the script author decide which is best.
1287
1288 If your script works with huge numbers and Calc is too slow for them,
1289 you can also for the loading of one of these libraries and if none of
1290 them can be used, the code will die:
1291
1292 use Math::BigInt only => 'GMP,Pari';
1293
1294 The following would first try to find Math::BigInt::Foo, then
1295 Math::BigInt::Bar, and when this also fails, revert to
1296 Math::BigInt::Calc:
1297
1298 use Math::BigInt try => 'Foo,Math::BigInt::Bar';
1299
1300 The library that is loaded last will be used. Note that this can be
1301 overwritten at any time by loading a different library, and numbers
1302 constructed with different libraries cannot be used in math operations
1303 together.
1304
1305 What library to use?
1306
1307 Note: General purpose packages should not be explicit about the library
1308 to use; let the script author decide which is best.
1309
1310 Math::BigInt::GMP and Math::BigInt::Pari are in cases involving big
1311 numbers much faster than Calc, however it is slower when dealing with
1312 very small numbers (less than about 20 digits) and when converting very
1313 large numbers to decimal (for instance for printing, rounding,
1314 calculating their length in decimal etc).
1315
1316 So please select carefully what library you want to use.
1317
1318 Different low-level libraries use different formats to store the
1319 numbers. However, you should NOT depend on the number having a
1320 specific format internally.
1321
1322 See the respective math library module documentation for further
1323 details.
1324
1325 SIGN
1326 The sign is either '+', '-', 'NaN', '+inf' or '-inf'.
1327
1328 A sign of 'NaN' is used to represent the result when input arguments
1329 are not numbers or as a result of 0/0. '+inf' and '-inf' represent plus
1330 respectively minus infinity. You will get '+inf' when dividing a
1331 positive number by 0, and '-inf' when dividing any negative number by
1332 0.
1333
1334 mantissa(), exponent() and parts()
1335 "mantissa()" and "exponent()" return the said parts of the BigInt such
1336 that:
1337
1338 $m = $x->mantissa();
1339 $e = $x->exponent();
1340 $y = $m * ( 10 ** $e );
1341 print "ok\n" if $x == $y;
1342
1343 "($m,$e) = $x->parts()" is just a shortcut that gives you both of them
1344 in one go. Both the returned mantissa and exponent have a sign.
1345
1346 Currently, for BigInts $e is always 0, except +inf and -inf, where it
1347 is "+inf"; and for NaN, where it is "NaN"; and for "$x == 0", where it
1348 is 1 (to be compatible with Math::BigFloat's internal representation of
1349 a zero as 0E1).
1350
1351 $m is currently just a copy of the original number. The relation
1352 between $e and $m will stay always the same, though their real values
1353 might change.
1354
1356 use Math::BigInt;
1357
1358 sub bint { Math::BigInt->new(shift); }
1359
1360 $x = Math::BigInt->bstr("1234") # string "1234"
1361 $x = "$x"; # same as bstr()
1362 $x = Math::BigInt->bneg("1234"); # BigInt "-1234"
1363 $x = Math::BigInt->babs("-12345"); # BigInt "12345"
1364 $x = Math::BigInt->bnorm("-0.00"); # BigInt "0"
1365 $x = bint(1) + bint(2); # BigInt "3"
1366 $x = bint(1) + "2"; # ditto (auto-BigIntify of "2")
1367 $x = bint(1); # BigInt "1"
1368 $x = $x + 5 / 2; # BigInt "3"
1369 $x = $x ** 3; # BigInt "27"
1370 $x *= 2; # BigInt "54"
1371 $x = Math::BigInt->new(0); # BigInt "0"
1372 $x--; # BigInt "-1"
1373 $x = Math::BigInt->badd(4,5) # BigInt "9"
1374 print $x->bsstr(); # 9e+0
1375
1376 Examples for rounding:
1377
1378 use Math::BigFloat;
1379 use Test;
1380
1381 $x = Math::BigFloat->new(123.4567);
1382 $y = Math::BigFloat->new(123.456789);
1383 Math::BigFloat->accuracy(4); # no more A than 4
1384
1385 ok ($x->copy()->fround(),123.4); # even rounding
1386 print $x->copy()->fround(),"\n"; # 123.4
1387 Math::BigFloat->round_mode('odd'); # round to odd
1388 print $x->copy()->fround(),"\n"; # 123.5
1389 Math::BigFloat->accuracy(5); # no more A than 5
1390 Math::BigFloat->round_mode('odd'); # round to odd
1391 print $x->copy()->fround(),"\n"; # 123.46
1392 $y = $x->copy()->fround(4),"\n"; # A = 4: 123.4
1393 print "$y, ",$y->accuracy(),"\n"; # 123.4, 4
1394
1395 Math::BigFloat->accuracy(undef); # A not important now
1396 Math::BigFloat->precision(2); # P important
1397 print $x->copy()->bnorm(),"\n"; # 123.46
1398 print $x->copy()->fround(),"\n"; # 123.46
1399
1400 Examples for converting:
1401
1402 my $x = Math::BigInt->new('0b1'.'01' x 123);
1403 print "bin: ",$x->as_bin()," hex:",$x->as_hex()," dec: ",$x,"\n";
1404
1406 After "use Math::BigInt ':constant'" all the integer decimal,
1407 hexadecimal and binary constants in the given scope are converted to
1408 "Math::BigInt". This conversion happens at compile time.
1409
1410 In particular,
1411
1412 perl -MMath::BigInt=:constant -e 'print 2**100,"\n"'
1413
1414 prints the integer value of "2**100". Note that without conversion of
1415 constants the expression 2**100 will be calculated as perl scalar.
1416
1417 Please note that strings and floating point constants are not affected,
1418 so that
1419
1420 use Math::BigInt qw/:constant/;
1421
1422 $x = 1234567890123456789012345678901234567890
1423 + 123456789123456789;
1424 $y = '1234567890123456789012345678901234567890'
1425 + '123456789123456789';
1426
1427 do not work. You need an explicit Math::BigInt->new() around one of the
1428 operands. You should also quote large constants to protect loss of
1429 precision:
1430
1431 use Math::BigInt;
1432
1433 $x = Math::BigInt->new('1234567889123456789123456789123456789');
1434
1435 Without the quotes Perl would convert the large number to a floating
1436 point constant at compile time and then hand the result to BigInt,
1437 which results in an truncated result or a NaN.
1438
1439 This also applies to integers that look like floating point constants:
1440
1441 use Math::BigInt ':constant';
1442
1443 print ref(123e2),"\n";
1444 print ref(123.2e2),"\n";
1445
1446 will print nothing but newlines. Use either bignum or Math::BigFloat to
1447 get this to work.
1448
1450 Using the form $x += $y; etc over $x = $x + $y is faster, since a copy
1451 of $x must be made in the second case. For long numbers, the copy can
1452 eat up to 20% of the work (in the case of addition/subtraction, less
1453 for multiplication/division). If $y is very small compared to $x, the
1454 form $x += $y is MUCH faster than $x = $x + $y since making the copy of
1455 $x takes more time then the actual addition.
1456
1457 With a technique called copy-on-write, the cost of copying with
1458 overload could be minimized or even completely avoided. A test
1459 implementation of COW did show performance gains for overloaded math,
1460 but introduced a performance loss due to a constant overhead for all
1461 other operations. So Math::BigInt does currently not COW.
1462
1463 The rewritten version of this module (vs. v0.01) is slower on certain
1464 operations, like "new()", "bstr()" and "numify()". The reason are that
1465 it does now more work and handles much more cases. The time spent in
1466 these operations is usually gained in the other math operations so that
1467 code on the average should get (much) faster. If they don't, please
1468 contact the author.
1469
1470 Some operations may be slower for small numbers, but are significantly
1471 faster for big numbers. Other operations are now constant (O(1), like
1472 "bneg()", "babs()" etc), instead of O(N) and thus nearly always take
1473 much less time. These optimizations were done on purpose.
1474
1475 If you find the Calc module to slow, try to install any of the
1476 replacement modules and see if they help you.
1477
1478 Alternative math libraries
1479 You can use an alternative library to drive Math::BigInt. See the
1480 section "MATH LIBRARY" for more information.
1481
1482 For more benchmark results see
1483 <http://bloodgate.com/perl/benchmarks.html>.
1484
1486 Subclassing Math::BigInt
1487 The basic design of Math::BigInt allows simple subclasses with very
1488 little work, as long as a few simple rules are followed:
1489
1490 · The public API must remain consistent, i.e. if a sub-class is
1491 overloading addition, the sub-class must use the same name, in this
1492 case badd(). The reason for this is that Math::BigInt is optimized to
1493 call the object methods directly.
1494
1495 · The private object hash keys like "$x->{sign}" may not be changed,
1496 but additional keys can be added, like "$x->{_custom}".
1497
1498 · Accessor functions are available for all existing object hash keys
1499 and should be used instead of directly accessing the internal hash
1500 keys. The reason for this is that Math::BigInt itself has a pluggable
1501 interface which permits it to support different storage methods.
1502
1503 More complex sub-classes may have to replicate more of the logic
1504 internal of Math::BigInt if they need to change more basic behaviors. A
1505 subclass that needs to merely change the output only needs to overload
1506 "bstr()".
1507
1508 All other object methods and overloaded functions can be directly
1509 inherited from the parent class.
1510
1511 At the very minimum, any subclass will need to provide its own "new()"
1512 and can store additional hash keys in the object. There are also some
1513 package globals that must be defined, e.g.:
1514
1515 # Globals
1516 $accuracy = undef;
1517 $precision = -2; # round to 2 decimal places
1518 $round_mode = 'even';
1519 $div_scale = 40;
1520
1521 Additionally, you might want to provide the following two globals to
1522 allow auto-upgrading and auto-downgrading to work correctly:
1523
1524 $upgrade = undef;
1525 $downgrade = undef;
1526
1527 This allows Math::BigInt to correctly retrieve package globals from the
1528 subclass, like $SubClass::precision. See t/Math/BigInt/Subclass.pm or
1529 t/Math/BigFloat/SubClass.pm completely functional subclass examples.
1530
1531 Don't forget to
1532
1533 use overload;
1534
1535 in your subclass to automatically inherit the overloading from the
1536 parent. If you like, you can change part of the overloading, look at
1537 Math::String for an example.
1538
1540 When used like this:
1541
1542 use Math::BigInt upgrade => 'Foo::Bar';
1543
1544 certain operations will 'upgrade' their calculation and thus the result
1545 to the class Foo::Bar. Usually this is used in conjunction with
1546 Math::BigFloat:
1547
1548 use Math::BigInt upgrade => 'Math::BigFloat';
1549
1550 As a shortcut, you can use the module "bignum":
1551
1552 use bignum;
1553
1554 Also good for one-liners:
1555
1556 perl -Mbignum -le 'print 2 ** 255'
1557
1558 This makes it possible to mix arguments of different classes (as in 2.5
1559 + 2) as well es preserve accuracy (as in sqrt(3)).
1560
1561 Beware: This feature is not fully implemented yet.
1562
1563 Auto-upgrade
1564 The following methods upgrade themselves unconditionally; that is if
1565 upgrade is in effect, they will always hand up their work:
1566
1567 bsqrt()
1568 div()
1569 blog()
1570 bexp()
1571
1572 Beware: This list is not complete.
1573
1574 All other methods upgrade themselves only when one (or all) of their
1575 arguments are of the class mentioned in $upgrade (This might change in
1576 later versions to a more sophisticated scheme):
1577
1579 "Math::BigInt" exports nothing by default, but can export the following
1580 methods:
1581
1582 bgcd
1583 blcm
1584
1586 Some things might not work as you expect them. Below is documented what
1587 is known to be troublesome:
1588
1589 bstr(), bsstr() and 'cmp'
1590 Both "bstr()" and "bsstr()" as well as automated stringify via
1591 overload now drop the leading '+'. The old code would return '+3', the
1592 new returns '3'. This is to be consistent with Perl and to make "cmp"
1593 (especially with overloading) to work as you expect. It also solves
1594 problems with "Test.pm", because its "ok()" uses 'eq' internally.
1595
1596 Mark Biggar said, when asked about to drop the '+' altogether, or make
1597 only "cmp" work:
1598
1599 I agree (with the first alternative), don't add the '+' on positive
1600 numbers. It's not as important anymore with the new internal
1601 form for numbers. It made doing things like abs and neg easier,
1602 but those have to be done differently now anyway.
1603
1604 So, the following examples will now work all as expected:
1605
1606 use Test;
1607 BEGIN { plan tests => 1 }
1608 use Math::BigInt;
1609
1610 my $x = new Math::BigInt 3*3;
1611 my $y = new Math::BigInt 3*3;
1612
1613 ok ($x,3*3);
1614 print "$x eq 9" if $x eq $y;
1615 print "$x eq 9" if $x eq '9';
1616 print "$x eq 9" if $x eq 3*3;
1617
1618 Additionally, the following still works:
1619
1620 print "$x == 9" if $x == $y;
1621 print "$x == 9" if $x == 9;
1622 print "$x == 9" if $x == 3*3;
1623
1624 There is now a "bsstr()" method to get the string in scientific
1625 notation aka 1e+2 instead of 100. Be advised that overloaded 'eq'
1626 always uses bstr() for comparison, but Perl will represent some
1627 numbers as 100 and others as 1e+308. If in doubt, convert both
1628 arguments to Math::BigInt before comparing them as strings:
1629
1630 use Test;
1631 BEGIN { plan tests => 3 }
1632 use Math::BigInt;
1633
1634 $x = Math::BigInt->new('1e56'); $y = 1e56;
1635 ok ($x,$y); # will fail
1636 ok ($x->bsstr(),$y); # okay
1637 $y = Math::BigInt->new($y);
1638 ok ($x,$y); # okay
1639
1640 Alternatively, simple use "<=>" for comparisons, this will get it
1641 always right. There is not yet a way to get a number automatically
1642 represented as a string that matches exactly the way Perl represents
1643 it.
1644
1645 See also the section about "Infinity and Not a Number" for problems in
1646 comparing NaNs.
1647
1648 int()
1649 "int()" will return (at least for Perl v5.7.1 and up) another BigInt,
1650 not a Perl scalar:
1651
1652 $x = Math::BigInt->new(123);
1653 $y = int($x); # BigInt 123
1654 $x = Math::BigFloat->new(123.45);
1655 $y = int($x); # BigInt 123
1656
1657 In all Perl versions you can use "as_number()" or "as_int" for the
1658 same effect:
1659
1660 $x = Math::BigFloat->new(123.45);
1661 $y = $x->as_number(); # BigInt 123
1662 $y = $x->as_int(); # ditto
1663
1664 This also works for other subclasses, like Math::String.
1665
1666 If you want a real Perl scalar, use "numify()":
1667
1668 $y = $x->numify(); # 123 as scalar
1669
1670 This is seldom necessary, though, because this is done automatically,
1671 like when you access an array:
1672
1673 $z = $array[$x]; # does work automatically
1674
1675 length
1676 The following will probably not do what you expect:
1677
1678 $c = Math::BigInt->new(123);
1679 print $c->length(),"\n"; # prints 30
1680
1681 It prints both the number of digits in the number and in the fraction
1682 part since print calls "length()" in list context. Use something like:
1683
1684 print scalar $c->length(),"\n"; # prints 3
1685
1686 bdiv
1687 The following will probably not do what you expect:
1688
1689 print $c->bdiv(10000),"\n";
1690
1691 It prints both quotient and remainder since print calls "bdiv()" in
1692 list context. Also, "bdiv()" will modify $c, so be careful. You
1693 probably want to use
1694
1695 print $c / 10000,"\n";
1696 print scalar $c->bdiv(10000),"\n"; # or if you want to modify $c
1697
1698 instead.
1699
1700 The quotient is always the greatest integer less than or equal to the
1701 real-valued quotient of the two operands, and the remainder (when it
1702 is non-zero) always has the same sign as the second operand; so, for
1703 example,
1704
1705 1 / 4 => ( 0, 1)
1706 1 / -4 => (-1,-3)
1707 -3 / 4 => (-1, 1)
1708 -3 / -4 => ( 0,-3)
1709 -11 / 2 => (-5,1)
1710 11 /-2 => (-5,-1)
1711
1712 As a consequence, the behavior of the operator % agrees with the
1713 behavior of Perl's built-in % operator (as documented in the perlop
1714 manpage), and the equation
1715
1716 $x == ($x / $y) * $y + ($x % $y)
1717
1718 holds true for any $x and $y, which justifies calling the two return
1719 values of bdiv() the quotient and remainder. The only exception to
1720 this rule are when $y == 0 and $x is negative, then the remainder will
1721 also be negative. See below under "infinity handling" for the
1722 reasoning behind this.
1723
1724 Perl's 'use integer;' changes the behaviour of % and / for scalars,
1725 but will not change BigInt's way to do things. This is because under
1726 'use integer' Perl will do what the underlying C thinks is right and
1727 this is different for each system. If you need BigInt's behaving
1728 exactly like Perl's 'use integer', bug the author to implement it ;)
1729
1730 infinity handling
1731 Here are some examples that explain the reasons why certain results
1732 occur while handling infinity:
1733
1734 The following table shows the result of the division and the
1735 remainder, so that the equation above holds true. Some "ordinary"
1736 cases are strewn in to show more clearly the reasoning:
1737
1738 A / B = C, R so that C * B + R = A
1739 =========================================================
1740 5 / 8 = 0, 5 0 * 8 + 5 = 5
1741 0 / 8 = 0, 0 0 * 8 + 0 = 0
1742 0 / inf = 0, 0 0 * inf + 0 = 0
1743 0 /-inf = 0, 0 0 * -inf + 0 = 0
1744 5 / inf = 0, 5 0 * inf + 5 = 5
1745 5 /-inf = 0, 5 0 * -inf + 5 = 5
1746 -5/ inf = 0, -5 0 * inf + -5 = -5
1747 -5/-inf = 0, -5 0 * -inf + -5 = -5
1748 inf/ 5 = inf, 0 inf * 5 + 0 = inf
1749 -inf/ 5 = -inf, 0 -inf * 5 + 0 = -inf
1750 inf/ -5 = -inf, 0 -inf * -5 + 0 = inf
1751 -inf/ -5 = inf, 0 inf * -5 + 0 = -inf
1752 5/ 5 = 1, 0 1 * 5 + 0 = 5
1753 -5/ -5 = 1, 0 1 * -5 + 0 = -5
1754 inf/ inf = 1, 0 1 * inf + 0 = inf
1755 -inf/-inf = 1, 0 1 * -inf + 0 = -inf
1756 inf/-inf = -1, 0 -1 * -inf + 0 = inf
1757 -inf/ inf = -1, 0 1 * -inf + 0 = -inf
1758 8/ 0 = inf, 8 inf * 0 + 8 = 8
1759 inf/ 0 = inf, inf inf * 0 + inf = inf
1760 0/ 0 = NaN
1761
1762 These cases below violate the "remainder has the sign of the second of
1763 the two arguments", since they wouldn't match up otherwise.
1764
1765 A / B = C, R so that C * B + R = A
1766 ========================================================
1767 -inf/ 0 = -inf, -inf -inf * 0 + inf = -inf
1768 -8/ 0 = -inf, -8 -inf * 0 + 8 = -8
1769
1770 Modifying and =
1771 Beware of:
1772
1773 $x = Math::BigFloat->new(5);
1774 $y = $x;
1775
1776 It will not do what you think, e.g. making a copy of $x. Instead it
1777 just makes a second reference to the same object and stores it in $y.
1778 Thus anything that modifies $x (except overloaded operators) will
1779 modify $y, and vice versa. Or in other words, "=" is only safe if you
1780 modify your BigInts only via overloaded math. As soon as you use a
1781 method call it breaks:
1782
1783 $x->bmul(2);
1784 print "$x, $y\n"; # prints '10, 10'
1785
1786 If you want a true copy of $x, use:
1787
1788 $y = $x->copy();
1789
1790 You can also chain the calls like this, this will make first a copy
1791 and then multiply it by 2:
1792
1793 $y = $x->copy()->bmul(2);
1794
1795 See also the documentation for overload.pm regarding "=".
1796
1797 bpow
1798 "bpow()" (and the rounding functions) now modifies the first argument
1799 and returns it, unlike the old code which left it alone and only
1800 returned the result. This is to be consistent with "badd()" etc. The
1801 first three will modify $x, the last one won't:
1802
1803 print bpow($x,$i),"\n"; # modify $x
1804 print $x->bpow($i),"\n"; # ditto
1805 print $x **= $i,"\n"; # the same
1806 print $x ** $i,"\n"; # leave $x alone
1807
1808 The form "$x **= $y" is faster than "$x = $x ** $y;", though.
1809
1810 Overloading -$x
1811 The following:
1812
1813 $x = -$x;
1814
1815 is slower than
1816
1817 $x->bneg();
1818
1819 since overload calls "sub($x,0,1);" instead of "neg($x)". The first
1820 variant needs to preserve $x since it does not know that it later will
1821 get overwritten. This makes a copy of $x and takes O(N), but
1822 $x->bneg() is O(1).
1823
1824 Mixing different object types
1825 In Perl you will get a floating point value if you do one of the
1826 following:
1827
1828 $float = 5.0 + 2;
1829 $float = 2 + 5.0;
1830 $float = 5 / 2;
1831
1832 With overloaded math, only the first two variants will result in a
1833 BigFloat:
1834
1835 use Math::BigInt;
1836 use Math::BigFloat;
1837
1838 $mbf = Math::BigFloat->new(5);
1839 $mbi2 = Math::BigInteger->new(5);
1840 $mbi = Math::BigInteger->new(2);
1841
1842 # what actually gets called:
1843 $float = $mbf + $mbi; # $mbf->badd()
1844 $float = $mbf / $mbi; # $mbf->bdiv()
1845 $integer = $mbi + $mbf; # $mbi->badd()
1846 $integer = $mbi2 / $mbi; # $mbi2->bdiv()
1847 $integer = $mbi2 / $mbf; # $mbi2->bdiv()
1848
1849 This is because math with overloaded operators follows the first
1850 (dominating) operand, and the operation of that is called and returns
1851 thus the result. So, Math::BigInt::bdiv() will always return a
1852 Math::BigInt, regardless whether the result should be a Math::BigFloat
1853 or the second operant is one.
1854
1855 To get a Math::BigFloat you either need to call the operation
1856 manually, make sure the operands are already of the proper type or
1857 casted to that type via Math::BigFloat->new():
1858
1859 $float = Math::BigFloat->new($mbi2) / $mbi; # = 2.5
1860
1861 Beware of simple "casting" the entire expression, this would only
1862 convert the already computed result:
1863
1864 $float = Math::BigFloat->new($mbi2 / $mbi); # = 2.0 thus wrong!
1865
1866 Beware also of the order of more complicated expressions like:
1867
1868 $integer = ($mbi2 + $mbi) / $mbf; # int / float => int
1869 $integer = $mbi2 / Math::BigFloat->new($mbi); # ditto
1870
1871 If in doubt, break the expression into simpler terms, or cast all
1872 operands to the desired resulting type.
1873
1874 Scalar values are a bit different, since:
1875
1876 $float = 2 + $mbf;
1877 $float = $mbf + 2;
1878
1879 will both result in the proper type due to the way the overloaded math
1880 works.
1881
1882 This section also applies to other overloaded math packages, like
1883 Math::String.
1884
1885 One solution to you problem might be autoupgrading|upgrading. See the
1886 pragmas bignum, bigint and bigrat for an easy way to do this.
1887
1888 bsqrt()
1889 "bsqrt()" works only good if the result is a big integer, e.g. the
1890 square root of 144 is 12, but from 12 the square root is 3, regardless
1891 of rounding mode. The reason is that the result is always truncated to
1892 an integer.
1893
1894 If you want a better approximation of the square root, then use:
1895
1896 $x = Math::BigFloat->new(12);
1897 Math::BigFloat->precision(0);
1898 Math::BigFloat->round_mode('even');
1899 print $x->copy->bsqrt(),"\n"; # 4
1900
1901 Math::BigFloat->precision(2);
1902 print $x->bsqrt(),"\n"; # 3.46
1903 print $x->bsqrt(3),"\n"; # 3.464
1904
1905 brsft()
1906 For negative numbers in base see also brsft.
1907
1909 This program is free software; you may redistribute it and/or modify it
1910 under the same terms as Perl itself.
1911
1913 Math::BigFloat, Math::BigRat and Math::Big as well as
1914 Math::BigInt::BitVect, Math::BigInt::Pari and Math::BigInt::GMP.
1915
1916 The pragmas bignum, bigint and bigrat also might be of interest because
1917 they solve the autoupgrading/downgrading issue, at least partly.
1918
1919 The package at
1920 <http://search.cpan.org/search?mode=module&query=Math%3A%3ABigInt>
1921 contains more documentation including a full version history,
1922 testcases, empty subclass files and benchmarks.
1923
1925 Original code by Mark Biggar, overloaded interface by Ilya Zakharevich.
1926 Completely rewritten by Tels http://bloodgate.com in late 2000, 2001 -
1927 2006 and still at it in 2007.
1928
1929 Many people contributed in one or more ways to the final beast, see the
1930 file CREDITS for an (incomplete) list. If you miss your name, please
1931 drop me a mail. Thank you!
1932
1933
1934
1935perl v5.16.3 2019-01-21 Math::BigInt(3pm)