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