1Math::BigInt(3pm)      Perl Programmers Reference Guide      Math::BigInt(3pm)
2
3
4

NAME

6       Math::BigInt - Arbitrary size integer/float math package
7

SYNOPSIS

9         use Math::BigInt;
10
11         # or make it faster with huge numbers: install (optional)
12         # Math::BigInt::GMP and always use (it 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 supress 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 preserve
68         # $x, use $z = $x->copy()->bXXX($y); See under L<CAVEATS> for why this is
69         # necessary when mixing $a = $b assignments with non-overloaded math.
70
71         $x->bzero();          # set $x to 0
72         $x->bnan();           # set $x to NaN
73         $x->bone();           # set $x to +1
74         $x->bone('-');        # set $x to -1
75         $x->binf();           # set $x to inf
76         $x->binf('-');        # set $x to -inf
77
78         $x->bneg();           # negation
79         $x->babs();           # absolute value
80         $x->bnorm();          # normalize (no-op in BigInt)
81         $x->bnot();           # two's complement (bit wise not)
82         $x->binc();           # increment $x by 1
83         $x->bdec();           # decrement $x by 1
84
85         $x->badd($y);         # addition (add $y to $x)
86         $x->bsub($y);         # subtraction (subtract $y from $x)
87         $x->bmul($y);         # multiplication (multiply $x by $y)
88         $x->bdiv($y);         # divide, set $x to quotient
89                               # return (quo,rem) or quo if scalar
90
91         $x->bmuladd($y,$z);   # $x = $x * $y + $z
92
93         $x->bmod($y);            # modulus (x % y)
94         $x->bmodpow($exp,$mod);  # modular exponentation (($num**$exp) % $mod))
95         $x->bmodinv($mod);       # the inverse of $x in the given modulus $mod
96
97         $x->bpow($y);            # power of arguments (x ** y)
98         $x->blsft($y);           # left shift in base 2
99         $x->brsft($y);           # right shift in base 2
100                                  # returns (quo,rem) or quo if in scalar context
101         $x->blsft($y,$n);        # left shift by $y places in base $n
102         $x->brsft($y,$n);        # right shift by $y places in base $n
103                                  # returns (quo,rem) or quo if in scalar context
104
105         $x->band($y);            # bitwise and
106         $x->bior($y);            # bitwise inclusive or
107         $x->bxor($y);            # bitwise exclusive or
108         $x->bnot();              # bitwise not (two's complement)
109
110         $x->bsqrt();             # calculate square-root
111         $x->broot($y);           # $y'th root of $x (e.g. $y == 3 => cubic root)
112         $x->bfac();              # factorial of $x (1*2*3*4*..$x)
113
114         $x->bnok($y);            # x over y (binomial coefficient n over k)
115
116         $x->blog();              # logarithm of $x to base e (Euler's number)
117         $x->blog($base);         # logarithm of $x to base $base (f.i. 2)
118         $x->bexp();              # calculate e ** $x where e is Euler's number
119
120         $x->round($A,$P,$mode);  # round to accuracy or precision using mode $mode
121         $x->bround($n);          # accuracy: preserve $n digits
122         $x->bfround($n);         # $n > 0: round $nth digits,
123                                  # $n < 0: round to the $nth digit after the
124                                  # dot, no-op for BigInts
125
126         # The following do not modify their arguments in BigInt (are no-ops),
127         # but do so in BigFloat:
128
129         $x->bfloor();            # return integer less or equal than $x
130         $x->bceil();             # return integer greater or equal than $x
131
132         # The following do not modify their arguments:
133
134         # greatest common divisor (no OO style)
135         my $gcd = Math::BigInt::bgcd(@values);
136         # lowest common multiplicator (no OO style)
137         my $lcm = Math::BigInt::blcm(@values);
138
139         $x->length();            # return number of digits in number
140         ($xl,$f) = $x->length(); # length of number and length of fraction part,
141                                  # latter is always 0 digits long for BigInts
142
143         $x->exponent();          # return exponent as BigInt
144         $x->mantissa();          # return (signed) mantissa as BigInt
145         $x->parts();             # return (mantissa,exponent) as BigInt
146         $x->copy();              # make a true copy of $x (unlike $y = $x;)
147         $x->as_int();            # return as BigInt (in BigInt: same as copy())
148         $x->numify();            # return as scalar (might overflow!)
149
150         # conversation to string (do not modify their argument)
151         $x->bstr();              # normalized string (e.g. '3')
152         $x->bsstr();             # norm. string in scientific notation (e.g. '3E0')
153         $x->as_hex();            # as signed hexadecimal string with prefixed 0x
154         $x->as_bin();            # as signed binary string with prefixed 0b
155         $x->as_oct();            # as signed octal string with prefixed 0
156
157
158         # precision and accuracy (see section about rounding for more)
159         $x->precision();         # return P of $x (or global, if P of $x undef)
160         $x->precision($n);       # set P of $x to $n
161         $x->accuracy();          # return A of $x (or global, if A of $x undef)
162         $x->accuracy($n);        # set A $x to $n
163
164         # Global methods
165         Math::BigInt->precision();    # get/set global P for all BigInt objects
166         Math::BigInt->accuracy();     # get/set global A for all BigInt objects
167         Math::BigInt->round_mode();   # get/set global round mode, one of
168                                       # 'even', 'odd', '+inf', '-inf', 'zero', 'trunc' or 'common'
169         Math::BigInt->config();       # return hash containing configuration
170

DESCRIPTION

172       All operators (including basic math operations) are overloaded if you
173       declare your big integers as
174
175         $i = new Math::BigInt '123_456_789_123_456_789';
176
177       Operations with overloaded operators preserve the arguments which is
178       exactly what you expect.
179
180       Input
181         Input values to these routines may be any string, that looks like a
182         number and results in an integer, including hexadecimal and binary
183         numbers.
184
185         Scalars holding numbers may also be passed, but note that non-integer
186         numbers may already have lost precision due to the conversation to
187         float. Quote your input if you want BigInt to see all the digits:
188
189                 $x = Math::BigInt->new(12345678890123456789);   # bad
190                 $x = Math::BigInt->new('12345678901234567890'); # good
191
192         You can include one underscore between any two digits.
193
194         This means integer values like 1.01E2 or even 1000E-2 are also
195         accepted.  Non-integer values result in NaN.
196
197         Hexadecimal (prefixed with "0x") and binary numbers (prefixed with
198         "0b") are accepted, too. Please note that octal numbers are not
199         recognized by new(), so the following will print "123":
200
201                 perl -MMath::BigInt -le 'print Math::BigInt->new("0123")'
202
203         To convert an octal number, use from_oct();
204
205                 perl -MMath::BigInt -le 'print Math::BigInt->from_oct("0123")'
206
207         Currently, Math::BigInt::new() defaults to 0, while
208         Math::BigInt::new('') results in 'NaN'. This might change in the
209         future, so use always the following explicit forms to get a zero or
210         NaN:
211
212                 $zero = Math::BigInt->bzero();
213                 $nan = Math::BigInt->bnan();
214
215         "bnorm()" on a BigInt object is now effectively a no-op, since the
216         numbers are always stored in normalized form. If passed a string,
217         creates a BigInt object from the input.
218
219       Output
220         Output values are BigInt objects (normalized), except for the methods
221         which return a string (see SYNOPSIS).
222
223         Some routines ("is_odd()", "is_even()", "is_zero()", "is_one()",
224         "is_nan()", etc.) return true or false, while others ("bcmp()",
225         "bacmp()") return either undef (if NaN is involved), <0, 0 or >0 and
226         are suited for sort.
227

METHODS

229       Each of the methods below (except config(), accuracy() and precision())
230       accepts three additional parameters. These arguments $A, $P and $R are
231       "accuracy", "precision" and "round_mode". Please see the section about
232       "ACCURACY and PRECISION" for more information.
233
234   config()
235               use Data::Dumper;
236
237               print Dumper ( Math::BigInt->config() );
238               print Math::BigInt->config()->{lib},"\n";
239
240       Returns a hash containing the configuration, e.g. the version number,
241       lib loaded etc. The following hash keys are currently filled in with
242       the appropriate information.
243
244               key             Description
245                               Example
246               ============================================================
247               lib             Name of the low-level math library
248                               Math::BigInt::Calc
249               lib_version     Version of low-level math library (see 'lib')
250                               0.30
251               class           The class name of config() you just called
252                               Math::BigInt
253               upgrade         To which class math operations might be upgraded
254                               Math::BigFloat
255               downgrade       To which class math operations might be downgraded
256                               undef
257               precision       Global precision
258                               undef
259               accuracy        Global accuracy
260                               undef
261               round_mode      Global round mode
262                               even
263               version         version number of the class you used
264                               1.61
265               div_scale       Fallback accuracy for div
266                               40
267               trap_nan        If true, traps creation of NaN via croak()
268                               1
269               trap_inf        If true, traps creation of +inf/-inf via croak()
270                               1
271
272       The following values can be set by passing "config()" a reference to a
273       hash:
274
275               trap_inf trap_nan
276               upgrade downgrade precision accuracy round_mode div_scale
277
278       Example:
279
280               $new_cfg = Math::BigInt->config( { trap_inf => 1, precision => 5 } );
281
282   accuracy()
283               $x->accuracy(5);                # local for $x
284               CLASS->accuracy(5);             # global for all members of CLASS
285                                               # Note: This also applies to new()!
286
287               $A = $x->accuracy();            # read out accuracy that affects $x
288               $A = CLASS->accuracy();         # read out global accuracy
289
290       Set or get the global or local accuracy, aka how many significant
291       digits the results have. If you set a global accuracy, then this also
292       applies to new()!
293
294       Warning! The accuracy sticks, e.g. once you created a number under the
295       influence of "CLASS->accuracy($A)", all results from math operations
296       with that number will also be rounded.
297
298       In most cases, you should probably round the results explicitly using
299       one of round(), bround() or bfround() or by passing the desired
300       accuracy to the math operation as additional parameter:
301
302               my $x = Math::BigInt->new(30000);
303               my $y = Math::BigInt->new(7);
304               print scalar $x->copy()->bdiv($y, 2);           # print 4300
305               print scalar $x->copy()->bdiv($y)->bround(2);   # print 4300
306
307       Please see the section about "ACCURACY AND PRECISION" for further
308       details.
309
310       Value must be greater than zero. Pass an undef value to disable it:
311
312               $x->accuracy(undef);
313               Math::BigInt->accuracy(undef);
314
315       Returns the current accuracy. For "$x-"accuracy()> it will return
316       either the local accuracy, or if not defined, the global. This means
317       the return value represents the accuracy that will be in effect for $x:
318
319               $y = Math::BigInt->new(1234567);        # unrounded
320               print Math::BigInt->accuracy(4),"\n";   # set 4, print 4
321               $x = Math::BigInt->new(123456);         # $x will be automatically rounded!
322               print "$x $y\n";                        # '123500 1234567'
323               print $x->accuracy(),"\n";              # will be 4
324               print $y->accuracy(),"\n";              # also 4, since global is 4
325               print Math::BigInt->accuracy(5),"\n";   # set to 5, print 5
326               print $x->accuracy(),"\n";              # still 4
327               print $y->accuracy(),"\n";              # 5, since global is 5
328
329       Note: Works also for subclasses like Math::BigFloat. Each class has
330       it's own globals separated from Math::BigInt, but it is possible to
331       subclass Math::BigInt and make the globals of the subclass aliases to
332       the ones from Math::BigInt.
333
334   precision()
335               $x->precision(-2);      # local for $x, round at the second digit right of the dot
336               $x->precision(2);       # ditto, round at the second digit left of the dot
337
338               CLASS->precision(5);    # Global for all members of CLASS
339                                       # This also applies to new()!
340               CLASS->precision(-5);   # ditto
341
342               $P = CLASS->precision();        # read out global precision
343               $P = $x->precision();           # read out precision that affects $x
344
345       Note: You probably want to use accuracy() instead. With accuracy you
346       set the number of digits each result should have, with precision you
347       set the place where to round!
348
349       "precision()" sets or gets the global or local precision, aka at which
350       digit before or after the dot to round all results. A set global
351       precision also applies to all newly created numbers!
352
353       In Math::BigInt, passing a negative number precision has no effect
354       since no numbers have digits after the dot. In Math::BigFloat, it will
355       round all results to P digits after the dot.
356
357       Please see the section about "ACCURACY AND PRECISION" for further
358       details.
359
360       Pass an undef value to disable it:
361
362               $x->precision(undef);
363               Math::BigInt->precision(undef);
364
365       Returns the current precision. For "$x-"precision()> it will return
366       either the local precision of $x, or if not defined, the global. This
367       means the return value represents the prevision that will be in effect
368       for $x:
369
370               $y = Math::BigInt->new(1234567);        # unrounded
371               print Math::BigInt->precision(4),"\n";  # set 4, print 4
372               $x = Math::BigInt->new(123456);         # will be automatically rounded
373               print $x;                               # print "120000"!
374
375       Note: Works also for subclasses like Math::BigFloat. Each class has its
376       own globals separated from Math::BigInt, but it is possible to subclass
377       Math::BigInt and make the globals of the subclass aliases to the ones
378       from Math::BigInt.
379
380   brsft()
381               $x->brsft($y,$n);
382
383       Shifts $x right by $y in base $n. Default is base 2, used are usually
384       10 and 2, but others work, too.
385
386       Right shifting usually amounts to dividing $x by $n ** $y and
387       truncating the result:
388
389               $x = Math::BigInt->new(10);
390               $x->brsft(1);                   # same as $x >> 1: 5
391               $x = Math::BigInt->new(1234);
392               $x->brsft(2,10);                # result 12
393
394       There is one exception, and that is base 2 with negative $x:
395
396               $x = Math::BigInt->new(-5);
397               print $x->brsft(1);
398
399       This will print -3, not -2 (as it would if you divide -5 by 2 and
400       truncate the result).
401
402   new()
403               $x = Math::BigInt->new($str,$A,$P,$R);
404
405       Creates a new BigInt object from a scalar or another BigInt object. The
406       input is accepted as decimal, hex (with leading '0x') or binary (with
407       leading '0b').
408
409       See Input for more info on accepted input formats.
410
411   from_oct()
412               $x = Math::BigInt->from_oct("0775");    # input is octal
413
414   from_hex()
415               $x = Math::BigInt->from_hex("0xcafe");  # input is hexadecimal
416
417   from_bin()
418               $x = Math::BigInt->from_oct("0x10011"); # input is binary
419
420   bnan()
421               $x = Math::BigInt->bnan();
422
423       Creates a new BigInt object representing NaN (Not A Number).  If used
424       on an object, it will set it to NaN:
425
426               $x->bnan();
427
428   bzero()
429               $x = Math::BigInt->bzero();
430
431       Creates a new BigInt object representing zero.  If used on an object,
432       it will set it to zero:
433
434               $x->bzero();
435
436   binf()
437               $x = Math::BigInt->binf($sign);
438
439       Creates a new BigInt object representing infinity. The optional
440       argument is either '-' or '+', indicating whether you want infinity or
441       minus infinity.  If used on an object, it will set it to infinity:
442
443               $x->binf();
444               $x->binf('-');
445
446   bone()
447               $x = Math::BigInt->binf($sign);
448
449       Creates a new BigInt object representing one. The optional argument is
450       either '-' or '+', indicating whether you want one or minus one.  If
451       used on an object, it will set it to one:
452
453               $x->bone();             # +1
454               $x->bone('-');          # -1
455
456   is_one()/is_zero()/is_nan()/is_inf()
457               $x->is_zero();                  # true if arg is +0
458               $x->is_nan();                   # true if arg is NaN
459               $x->is_one();                   # true if arg is +1
460               $x->is_one('-');                # true if arg is -1
461               $x->is_inf();                   # true if +inf
462               $x->is_inf('-');                # true if -inf (sign is default '+')
463
464       These methods all test the BigInt for being one specific value and
465       return true or false depending on the input. These are faster than
466       doing something like:
467
468               if ($x == 0)
469
470   is_pos()/is_neg()/is_positive()/is_negative()
471               $x->is_pos();                   # true if > 0
472               $x->is_neg();                   # true if < 0
473
474       The methods return true if the argument is positive or negative,
475       respectively.  "NaN" is neither positive nor negative, while "+inf"
476       counts as positive, and "-inf" is negative. A "zero" is neither
477       positive nor negative.
478
479       These methods are only testing the sign, and not the value.
480
481       "is_positive()" and "is_negative()" are aliases to "is_pos()" and
482       "is_neg()", respectively. "is_positive()" and "is_negative()" were
483       introduced in v1.36, while "is_pos()" and "is_neg()" were only
484       introduced in v1.68.
485
486   is_odd()/is_even()/is_int()
487               $x->is_odd();                   # true if odd, false for even
488               $x->is_even();                  # true if even, false for odd
489               $x->is_int();                   # true if $x is an integer
490
491       The return true when the argument satisfies the condition. "NaN",
492       "+inf", "-inf" are not integers and are neither odd nor even.
493
494       In BigInt, all numbers except "NaN", "+inf" and "-inf" are integers.
495
496   bcmp()
497               $x->bcmp($y);
498
499       Compares $x with $y and takes the sign into account.  Returns -1, 0, 1
500       or undef.
501
502   bacmp()
503               $x->bacmp($y);
504
505       Compares $x with $y while ignoring their. Returns -1, 0, 1 or undef.
506
507   sign()
508               $x->sign();
509
510       Return the sign, of $x, meaning either "+", "-", "-inf", "+inf" or NaN.
511
512       If you want $x to have a certain sign, use one of the following
513       methods:
514
515               $x->babs();             # '+'
516               $x->babs()->bneg();     # '-'
517               $x->bnan();             # 'NaN'
518               $x->binf();             # '+inf'
519               $x->binf('-');          # '-inf'
520
521   digit()
522               $x->digit($n);          # return the nth digit, counting from right
523
524       If $n is negative, returns the digit counting from left.
525
526   bneg()
527               $x->bneg();
528
529       Negate the number, e.g. change the sign between '+' and '-', or between
530       '+inf' and '-inf', respectively. Does nothing for NaN or zero.
531
532   babs()
533               $x->babs();
534
535       Set the number to its absolute value, e.g. change the sign from '-' to
536       '+' and from '-inf' to '+inf', respectively. Does nothing for NaN or
537       positive numbers.
538
539   bnorm()
540               $x->bnorm();                    # normalize (no-op)
541
542   bnot()
543               $x->bnot();
544
545       Two's complement (bitwise not). This is equivalent to
546
547               $x->binc()->bneg();
548
549       but faster.
550
551   binc()
552               $x->binc();                     # increment x by 1
553
554   bdec()
555               $x->bdec();                     # decrement x by 1
556
557   badd()
558               $x->badd($y);                   # addition (add $y to $x)
559
560   bsub()
561               $x->bsub($y);                   # subtraction (subtract $y from $x)
562
563   bmul()
564               $x->bmul($y);                   # multiplication (multiply $x by $y)
565
566   bmuladd()
567               $x->bmuladd($y,$z);
568
569       Multiply $x by $y, and then add $z to the result,
570
571       This method was added in v1.87 of Math::BigInt (June 2007).
572
573   bdiv()
574               $x->bdiv($y);                   # divide, set $x to quotient
575                                               # return (quo,rem) or quo if scalar
576
577   bmod()
578               $x->bmod($y);                   # modulus (x % y)
579
580   bmodinv()
581               num->bmodinv($mod);             # modular inverse
582
583       Returns the inverse of $num in the given modulus $mod.  '"NaN"' is
584       returned unless $num is relatively prime to $mod, i.e. unless
585       "bgcd($num, $mod)==1".
586
587   bmodpow()
588               $num->bmodpow($exp,$mod);       # modular exponentation
589                                               # ($num**$exp % $mod)
590
591       Returns the value of $num taken to the power $exp in the modulus $mod
592       using binary exponentation.  "bmodpow" is far superior to writing
593
594               $num ** $exp % $mod
595
596       because it is much faster - it reduces internal variables into the
597       modulus whenever possible, so it operates on smaller numbers.
598
599       "bmodpow" also supports negative exponents.
600
601               bmodpow($num, -1, $mod)
602
603       is exactly equivalent to
604
605               bmodinv($num, $mod)
606
607   bpow()
608               $x->bpow($y);                   # power of arguments (x ** y)
609
610   blog()
611               $x->blog($base, $accuracy);     # logarithm of x to the base $base
612
613       If $base is not defined, Euler's number (e) is used:
614
615               print $x->blog(undef, 100);     # log(x) to 100 digits
616
617   bexp()
618               $x->bexp($accuracy);            # calculate e ** X
619
620       Calculates the expression "e ** $x" where "e" is Euler's number.
621
622       This method was added in v1.82 of Math::BigInt (April 2007).
623
624       See also blog().
625
626   bnok()
627               $x->bnok($y);              # x over y (binomial coefficient n over k)
628
629       Calculates the binomial coefficient n over k, also called the "choose"
630       function. The result is equivalent to:
631
632               ( n )      n!
633               | - |  = -------
634               ( k )    k!(n-k)!
635
636       This method was added in v1.84 of Math::BigInt (April 2007).
637
638   bpi()
639               print Math::BigInt->bpi(100), "\n";             # 3
640
641       Returns PI truncated to an integer, with the argument being ignored.
642       This means under BigInt this always returns 3.
643
644       If upgrading is in effect, returns PI, rounded to N digits with the
645       current rounding mode:
646
647               use Math::BigFloat;
648               use Math::BigInt upgrade => Math::BigFloat;
649               print Math::BigInt->bpi(3), "\n";               # 3.14
650               print Math::BigInt->bpi(100), "\n";             # 3.1415....
651
652       This method was added in v1.87 of Math::BigInt (June 2007).
653
654   bcos()
655               my $x = Math::BigInt->new(1);
656               print $x->bcos(100), "\n";
657
658       Calculate the cosinus of $x, modifying $x in place.
659
660       In BigInt, unless upgrading is in effect, the result is truncated to an
661       integer.
662
663       This method was added in v1.87 of Math::BigInt (June 2007).
664
665   bsin()
666               my $x = Math::BigInt->new(1);
667               print $x->bsin(100), "\n";
668
669       Calculate the sinus of $x, modifying $x in place.
670
671       In BigInt, unless upgrading is in effect, the result is truncated to an
672       integer.
673
674       This method was added in v1.87 of Math::BigInt (June 2007).
675
676   batan2()
677               my $x = Math::BigInt->new(1);
678               my $y = Math::BigInt->new(1);
679               print $y->batan2($x), "\n";
680
681       Calculate the arcus tangens of $y divided by $x, modifying $y in place.
682
683       In BigInt, unless upgrading is in effect, the result is truncated to an
684       integer.
685
686       This method was added in v1.87 of Math::BigInt (June 2007).
687
688   batan()
689               my $x = Math::BigFloat->new(0.5);
690               print $x->batan(100), "\n";
691
692       Calculate the arcus tangens of $x, modifying $x in place.
693
694       In BigInt, unless upgrading is in effect, the result is truncated to an
695       integer.
696
697       This method was added in v1.87 of Math::BigInt (June 2007).
698
699   blsft()
700               $x->blsft($y);          # left shift in base 2
701               $x->blsft($y,$n);       # left shift, in base $n (like 10)
702
703   brsft()
704               $x->brsft($y);          # right shift in base 2
705               $x->brsft($y,$n);       # right shift, in base $n (like 10)
706
707   band()
708               $x->band($y);                   # bitwise and
709
710   bior()
711               $x->bior($y);                   # bitwise inclusive or
712
713   bxor()
714               $x->bxor($y);                   # bitwise exclusive or
715
716   bnot()
717               $x->bnot();                     # bitwise not (two's complement)
718
719   bsqrt()
720               $x->bsqrt();                    # calculate square-root
721
722   broot()
723               $x->broot($N);
724
725       Calculates the N'th root of $x.
726
727   bfac()
728               $x->bfac();                     # factorial of $x (1*2*3*4*..$x)
729
730   round()
731               $x->round($A,$P,$round_mode);
732
733       Round $x to accuracy $A or precision $P using the round mode
734       $round_mode.
735
736   bround()
737               $x->bround($N);               # accuracy: preserve $N digits
738
739   bfround()
740               $x->bfround($N);
741
742       If N is > 0, rounds to the Nth digit from the left. If N < 0, rounds to
743       the Nth digit after the dot. Since BigInts are integers, the case N < 0
744       is a no-op for them.
745
746       Examples:
747
748               Input           N               Result
749               ===================================================
750               123456.123456   3               123500
751               123456.123456   2               123450
752               123456.123456   -2              123456.12
753               123456.123456   -3              123456.123
754
755   bfloor()
756               $x->bfloor();
757
758       Set $x to the integer less or equal than $x. This is a no-op in BigInt,
759       but does change $x in BigFloat.
760
761   bceil()
762               $x->bceil();
763
764       Set $x to the integer greater or equal than $x. This is a no-op in
765       BigInt, but does change $x in BigFloat.
766
767   bgcd()
768               bgcd(@values);          # greatest common divisor (no OO style)
769
770   blcm()
771               blcm(@values);          # lowest common multiplicator (no OO style)
772
773       head2 length()
774
775               $x->length();
776               ($xl,$fl) = $x->length();
777
778       Returns the number of digits in the decimal representation of the
779       number.  In list context, returns the length of the integer and
780       fraction part. For BigInt's, the length of the fraction part will
781       always be 0.
782
783   exponent()
784               $x->exponent();
785
786       Return the exponent of $x as BigInt.
787
788   mantissa()
789               $x->mantissa();
790
791       Return the signed mantissa of $x as BigInt.
792
793   parts()
794               $x->parts();            # return (mantissa,exponent) as BigInt
795
796   copy()
797               $x->copy();             # make a true copy of $x (unlike $y = $x;)
798
799   as_int()/as_number()
800               $x->as_int();
801
802       Returns $x as a BigInt (truncated towards zero). In BigInt this is the
803       same as "copy()".
804
805       "as_number()" is an alias to this method. "as_number" was introduced in
806       v1.22, while "as_int()" was only introduced in v1.68.
807
808   bstr()
809               $x->bstr();
810
811       Returns a normalized string representation of $x.
812
813   bsstr()
814               $x->bsstr();            # normalized string in scientific notation
815
816   as_hex()
817               $x->as_hex();           # as signed hexadecimal string with prefixed 0x
818
819   as_bin()
820               $x->as_bin();           # as signed binary string with prefixed 0b
821
822   as_oct()
823               $x->as_oct();           # as signed octal string with prefixed 0
824
825   numify()
826               print $x->numify();
827
828       This returns a normal Perl scalar from $x. It is used automatically
829       whenever a scalar is needed, for instance in array index operations.
830
831       This loses precision, to avoid this use as_int() instead.
832
833   modify()
834               $x->modify('bpowd');
835
836       This method returns 0 if the object can be modified with the given
837       peration, or 1 if not.
838
839       This is used for instance by Math::BigInt::Constant.
840
841   upgrade()/downgrade()
842       Set/get the class for downgrade/upgrade operations. Thuis is used for
843       instance by bignum. The defaults are '', thus the following operation
844       will create a BigInt, not a BigFloat:
845
846               my $i = Math::BigInt->new(123);
847               my $f = Math::BigFloat->new('123.1');
848
849               print $i + $f,"\n";                     # print 246
850
851   div_scale()
852       Set/get the number of digits for the default precision in divide
853       operations.
854
855   round_mode()
856       Set/get the current round mode.
857

ACCURACY and PRECISION

859       Since version v1.33, Math::BigInt and Math::BigFloat have full support
860       for accuracy and precision based rounding, both automatically after
861       every operation, as well as manually.
862
863       This section describes the accuracy/precision handling in Math::Big* as
864       it used to be and as it is now, complete with an explanation of all
865       terms and abbreviations.
866
867       Not yet implemented things (but with correct description) are marked
868       with '!', things that need to be answered are marked with '?'.
869
870       In the next paragraph follows a short description of terms used here
871       (because these may differ from terms used by others people or
872       documentation).
873
874       During the rest of this document, the shortcuts A (for accuracy), P
875       (for precision), F (fallback) and R (rounding mode) will be used.
876
877   Precision P
878       A fixed number of digits before (positive) or after (negative) the
879       decimal point. For example, 123.45 has a precision of -2. 0 means an
880       integer like 123 (or 120). A precision of 2 means two digits to the
881       left of the decimal point are zero, so 123 with P = 1 becomes 120. Note
882       that numbers with zeros before the decimal point may have different
883       precisions, because 1200 can have p = 0, 1 or 2 (depending on what the
884       inital value was). It could also have p < 0, when the digits after the
885       decimal point are zero.
886
887       The string output (of floating point numbers) will be padded with
888       zeros:
889
890               Initial value   P       A       Result          String
891               ------------------------------------------------------------
892               1234.01         -3              1000            1000
893               1234            -2              1200            1200
894               1234.5          -1              1230            1230
895               1234.001        1               1234            1234.0
896               1234.01         0               1234            1234
897               1234.01         2               1234.01         1234.01
898               1234.01         5               1234.01         1234.01000
899
900       For BigInts, no padding occurs.
901
902   Accuracy A
903       Number of significant digits. Leading zeros are not counted. A number
904       may have an accuracy greater than the non-zero digits when there are
905       zeros in it or trailing zeros. For example, 123.456 has A of 6, 10203
906       has 5, 123.0506 has 7, 123.450000 has 8 and 0.000123 has 3.
907
908       The string output (of floating point numbers) will be padded with
909       zeros:
910
911               Initial value   P       A       Result          String
912               ------------------------------------------------------------
913               1234.01                 3       1230            1230
914               1234.01                 6       1234.01         1234.01
915               1234.1                  8       1234.1          1234.1000
916
917       For BigInts, no padding occurs.
918
919   Fallback F
920       When both A and P are undefined, this is used as a fallback accuracy
921       when dividing numbers.
922
923   Rounding mode R
924       When rounding a number, different 'styles' or 'kinds' of rounding are
925       possible. (Note that random rounding, as in Math::Round, is not
926       implemented.)
927
928       'trunc'
929         truncation invariably removes all digits following the rounding
930         place, replacing them with zeros. Thus, 987.65 rounded to tens (P=1)
931         becomes 980, and rounded to the fourth sigdig becomes 987.6 (A=4).
932         123.456 rounded to the second place after the decimal point (P=-2)
933         becomes 123.46.
934
935         All other implemented styles of rounding attempt to round to the
936         "nearest digit." If the digit D immediately to the right of the
937         rounding place (skipping the decimal point) is greater than 5, the
938         number is incremented at the rounding place (possibly causing a
939         cascade of incrementation): e.g. when rounding to units, 0.9 rounds
940         to 1, and -19.9 rounds to -20. If D < 5, the number is similarly
941         truncated at the rounding place: e.g. when rounding to units, 0.4
942         rounds to 0, and -19.4 rounds to -19.
943
944         However the results of other styles of rounding differ if the digit
945         immediately to the right of the rounding place (skipping the decimal
946         point) is 5 and if there are no digits, or no digits other than 0,
947         after that 5. In such cases:
948
949       'even'
950         rounds the digit at the rounding place to 0, 2, 4, 6, or 8 if it is
951         not already. E.g., when rounding to the first sigdig, 0.45 becomes
952         0.4, -0.55 becomes -0.6, but 0.4501 becomes 0.5.
953
954       'odd'
955         rounds the digit at the rounding place to 1, 3, 5, 7, or 9 if it is
956         not already. E.g., when rounding to the first sigdig, 0.45 becomes
957         0.5, -0.55 becomes -0.5, but 0.5501 becomes 0.6.
958
959       '+inf'
960         round to plus infinity, i.e. always round up. E.g., when rounding to
961         the first sigdig, 0.45 becomes 0.5, -0.55 becomes -0.5, and 0.4501
962         also becomes 0.5.
963
964       '-inf'
965         round to minus infinity, i.e. always round down. E.g., when rounding
966         to the first sigdig, 0.45 becomes 0.4, -0.55 becomes -0.6, but 0.4501
967         becomes 0.5.
968
969       'zero'
970         round to zero, i.e. positive numbers down, negative ones up.  E.g.,
971         when rounding to the first sigdig, 0.45 becomes 0.4, -0.55 becomes
972         -0.5, but 0.4501 becomes 0.5.
973
974       'common'
975         round up if the digit immediately to the right of the rounding place
976         is 5 or greater, otherwise round down. E.g., 0.15 becomes 0.2 and
977         0.149 becomes 0.1.
978
979       The handling of A & P in MBI/MBF (the old core code shipped with Perl
980       versions <= 5.7.2) is like this:
981
982       Precision
983           * ffround($p) is able to round to $p number of digits after the decimal
984             point
985           * otherwise P is unused
986
987       Accuracy (significant digits)
988           * fround($a) rounds to $a significant digits
989           * only fdiv() and fsqrt() take A as (optional) paramater
990             + other operations simply create the same number (fneg etc), or more (fmul)
991               of digits
992             + rounding/truncating is only done when explicitly calling one of fround
993               or ffround, and never for BigInt (not implemented)
994           * fsqrt() simply hands its accuracy argument over to fdiv.
995           * the documentation and the comment in the code indicate two different ways
996             on how fdiv() determines the maximum number of digits it should calculate,
997             and the actual code does yet another thing
998             POD:
999               max($Math::BigFloat::div_scale,length(dividend)+length(divisor))
1000             Comment:
1001               result has at most max(scale, length(dividend), length(divisor)) digits
1002             Actual code:
1003               scale = max(scale, length(dividend)-1,length(divisor)-1);
1004               scale += length(divisor) - length(dividend);
1005             So for lx = 3, ly = 9, scale = 10, scale will actually be 16 (10+9-3).
1006             Actually, the 'difference' added to the scale is calculated from the
1007             number of "significant digits" in dividend and divisor, which is derived
1008             by looking at the length of the mantissa. Which is wrong, since it includes
1009             the + sign (oops) and actually gets 2 for '+100' and 4 for '+101'. Oops
1010             again. Thus 124/3 with div_scale=1 will get you '41.3' based on the strange
1011             assumption that 124 has 3 significant digits, while 120/7 will get you
1012             '17', not '17.1' since 120 is thought to have 2 significant digits.
1013             The rounding after the division then uses the remainder and $y to determine
1014             wether it must round up or down.
1015          ?  I have no idea which is the right way. That's why I used a slightly more
1016          ?  simple scheme and tweaked the few failing testcases to match it.
1017
1018       This is how it works now:
1019
1020       Setting/Accessing
1021           * You can set the A global via C<< Math::BigInt->accuracy() >> or
1022             C<< Math::BigFloat->accuracy() >> or whatever class you are using.
1023           * You can also set P globally by using C<< Math::SomeClass->precision() >>
1024             likewise.
1025           * Globals are classwide, and not inherited by subclasses.
1026           * to undefine A, use C<< Math::SomeCLass->accuracy(undef); >>
1027           * to undefine P, use C<< Math::SomeClass->precision(undef); >>
1028           * Setting C<< Math::SomeClass->accuracy() >> clears automatically
1029             C<< Math::SomeClass->precision() >>, and vice versa.
1030           * To be valid, A must be > 0, P can have any value.
1031           * If P is negative, this means round to the P'th place to the right of the
1032             decimal point; positive values mean to the left of the decimal point.
1033             P of 0 means round to integer.
1034           * to find out the current global A, use C<< Math::SomeClass->accuracy() >>
1035           * to find out the current global P, use C<< Math::SomeClass->precision() >>
1036           * use C<< $x->accuracy() >> respective C<< $x->precision() >> for the local
1037             setting of C<< $x >>.
1038           * Please note that C<< $x->accuracy() >> respective C<< $x->precision() >>
1039             return eventually defined global A or P, when C<< $x >>'s A or P is not
1040             set.
1041
1042       Creating numbers
1043           * When you create a number, you can give the desired A or P via:
1044             $x = Math::BigInt->new($number,$A,$P);
1045           * Only one of A or P can be defined, otherwise the result is NaN
1046           * If no A or P is give ($x = Math::BigInt->new($number) form), then the
1047             globals (if set) will be used. Thus changing the global defaults later on
1048             will not change the A or P of previously created numbers (i.e., A and P of
1049             $x will be what was in effect when $x was created)
1050           * If given undef for A and P, B<no> rounding will occur, and the globals will
1051             B<not> be used. This is used by subclasses to create numbers without
1052             suffering rounding in the parent. Thus a subclass is able to have its own
1053             globals enforced upon creation of a number by using
1054             C<< $x = Math::BigInt->new($number,undef,undef) >>:
1055
1056                 use Math::BigInt::SomeSubclass;
1057                 use Math::BigInt;
1058
1059                 Math::BigInt->accuracy(2);
1060                 Math::BigInt::SomeSubClass->accuracy(3);
1061                 $x = Math::BigInt::SomeSubClass->new(1234);
1062
1063             $x is now 1230, and not 1200. A subclass might choose to implement
1064             this otherwise, e.g. falling back to the parent's A and P.
1065
1066       Usage
1067           * If A or P are enabled/defined, they are used to round the result of each
1068             operation according to the rules below
1069           * Negative P is ignored in Math::BigInt, since BigInts never have digits
1070             after the decimal point
1071           * Math::BigFloat uses Math::BigInt internally, but setting A or P inside
1072             Math::BigInt as globals does not tamper with the parts of a BigFloat.
1073             A flag is used to mark all Math::BigFloat numbers as 'never round'.
1074
1075       Precedence
1076           * It only makes sense that a number has only one of A or P at a time.
1077             If you set either A or P on one object, or globally, the other one will
1078             be automatically cleared.
1079           * If two objects are involved in an operation, and one of them has A in
1080             effect, and the other P, this results in an error (NaN).
1081           * A takes precedence over P (Hint: A comes before P).
1082             If neither of them is defined, nothing is used, i.e. the result will have
1083             as many digits as it can (with an exception for fdiv/fsqrt) and will not
1084             be rounded.
1085           * There is another setting for fdiv() (and thus for fsqrt()). If neither of
1086             A or P is defined, fdiv() will use a fallback (F) of $div_scale digits.
1087             If either the dividend's or the divisor's mantissa has more digits than
1088             the value of F, the higher value will be used instead of F.
1089             This is to limit the digits (A) of the result (just consider what would
1090             happen with unlimited A and P in the case of 1/3 :-)
1091           * fdiv will calculate (at least) 4 more digits than required (determined by
1092             A, P or F), and, if F is not used, round the result
1093             (this will still fail in the case of a result like 0.12345000000001 with A
1094             or P of 5, but this can not be helped - or can it?)
1095           * Thus you can have the math done by on Math::Big* class in two modi:
1096             + never round (this is the default):
1097               This is done by setting A and P to undef. No math operation
1098               will round the result, with fdiv() and fsqrt() as exceptions to guard
1099               against overflows. You must explicitly call bround(), bfround() or
1100               round() (the latter with parameters).
1101               Note: Once you have rounded a number, the settings will 'stick' on it
1102               and 'infect' all other numbers engaged in math operations with it, since
1103               local settings have the highest precedence. So, to get SaferRound[tm],
1104               use a copy() before rounding like this:
1105
1106                 $x = Math::BigFloat->new(12.34);
1107                 $y = Math::BigFloat->new(98.76);
1108                 $z = $x * $y;                           # 1218.6984
1109                 print $x->copy()->fround(3);            # 12.3 (but A is now 3!)
1110                 $z = $x * $y;                           # still 1218.6984, without
1111                                                         # copy would have been 1210!
1112
1113             + round after each op:
1114               After each single operation (except for testing like is_zero()), the
1115               method round() is called and the result is rounded appropriately. By
1116               setting proper values for A and P, you can have all-the-same-A or
1117               all-the-same-P modes. For example, Math::Currency might set A to undef,
1118               and P to -2, globally.
1119
1120          ?Maybe an extra option that forbids local A & P settings would be in order,
1121          ?so that intermediate rounding does not 'poison' further math?
1122
1123       Overriding globals
1124           * you will be able to give A, P and R as an argument to all the calculation
1125             routines; the second parameter is A, the third one is P, and the fourth is
1126             R (shift right by one for binary operations like badd). P is used only if
1127             the first parameter (A) is undefined. These three parameters override the
1128             globals in the order detailed as follows, i.e. the first defined value
1129             wins:
1130             (local: per object, global: global default, parameter: argument to sub)
1131               + parameter A
1132               + parameter P
1133               + local A (if defined on both of the operands: smaller one is taken)
1134               + local P (if defined on both of the operands: bigger one is taken)
1135               + global A
1136               + global P
1137               + global F
1138           * fsqrt() will hand its arguments to fdiv(), as it used to, only now for two
1139             arguments (A and P) instead of one
1140
1141       Local settings
1142           * You can set A or P locally by using C<< $x->accuracy() >> or
1143             C<< $x->precision() >>
1144             and thus force different A and P for different objects/numbers.
1145           * Setting A or P this way immediately rounds $x to the new value.
1146           * C<< $x->accuracy() >> clears C<< $x->precision() >>, and vice versa.
1147
1148       Rounding
1149           * the rounding routines will use the respective global or local settings.
1150             fround()/bround() is for accuracy rounding, while ffround()/bfround()
1151             is for precision
1152           * the two rounding functions take as the second parameter one of the
1153             following rounding modes (R):
1154             'even', 'odd', '+inf', '-inf', 'zero', 'trunc', 'common'
1155           * you can set/get the global R by using C<< Math::SomeClass->round_mode() >>
1156             or by setting C<< $Math::SomeClass::round_mode >>
1157           * after each operation, C<< $result->round() >> is called, and the result may
1158             eventually be rounded (that is, if A or P were set either locally,
1159             globally or as parameter to the operation)
1160           * to manually round a number, call C<< $x->round($A,$P,$round_mode); >>
1161             this will round the number by using the appropriate rounding function
1162             and then normalize it.
1163           * rounding modifies the local settings of the number:
1164
1165                 $x = Math::BigFloat->new(123.456);
1166                 $x->accuracy(5);
1167                 $x->bround(4);
1168
1169             Here 4 takes precedence over 5, so 123.5 is the result and $x->accuracy()
1170             will be 4 from now on.
1171
1172       Default values
1173           * R: 'even'
1174           * F: 40
1175           * A: undef
1176           * P: undef
1177
1178       Remarks
1179           * The defaults are set up so that the new code gives the same results as
1180             the old code (except in a few cases on fdiv):
1181             + Both A and P are undefined and thus will not be used for rounding
1182               after each operation.
1183             + round() is thus a no-op, unless given extra parameters A and P
1184

Infinity and Not a Number

1186       While BigInt has extensive handling of inf and NaN, certain quirks
1187       remain.
1188
1189       oct()/hex()
1190         These perl routines currently (as of Perl v.5.8.6) cannot handle
1191         passed inf.
1192
1193                 te@linux:~> perl -wle 'print 2 ** 3333'
1194                 inf
1195                 te@linux:~> perl -wle 'print 2 ** 3333 == 2 ** 3333'
1196                 1
1197                 te@linux:~> perl -wle 'print oct(2 ** 3333)'
1198                 0
1199                 te@linux:~> perl -wle 'print hex(2 ** 3333)'
1200                 Illegal hexadecimal digit 'i' ignored at -e line 1.
1201                 0
1202
1203         The same problems occur if you pass them Math::BigInt->binf()
1204         objects. Since overloading these routines is not possible, this
1205         cannot be fixed from BigInt.
1206
1207       ==, !=, <, >, <=, >= with NaNs
1208         BigInt's bcmp() routine currently returns undef to signal that a NaN
1209         was involved in a comparison. However, the overload code turns that
1210         into either 1 or '' and thus operations like "NaN != NaN" might
1211         return wrong values.
1212
1213       log(-inf)
1214         "log(-inf)" is highly weird. Since log(-x)=pi*i+log(x), then
1215         log(-inf)=pi*i+inf. However, since the imaginary part is finite, the
1216         real infinity "overshadows" it, so the number might as well just be
1217         infinity.  However, the result is a complex number, and since
1218         BigInt/BigFloat can only have real numbers as results, the result is
1219         NaN.
1220
1221       exp(), cos(), sin(), atan2()
1222         These all might have problems handling infinity right.
1223

INTERNALS

1225       The actual numbers are stored as unsigned big integers (with seperate
1226       sign).
1227
1228       You should neither care about nor depend on the internal
1229       representation; it might change without notice. Use ONLY method calls
1230       like "$x->sign();" instead relying on the internal representation.
1231
1232   MATH LIBRARY
1233       Math with the numbers is done (by default) by a module called
1234       "Math::BigInt::Calc". This is equivalent to saying:
1235
1236               use Math::BigInt try => 'Calc';
1237
1238       You can change this backend library by using:
1239
1240               use Math::BigInt try => 'GMP';
1241
1242       Note: General purpose packages should not be explicit about the library
1243       to use; let the script author decide which is best.
1244
1245       If your script works with huge numbers and Calc is too slow for them,
1246       you can also for the loading of one of these libraries and if none of
1247       them can be used, the code will die:
1248
1249               use Math::BigInt only => 'GMP,Pari';
1250
1251       The following would first try to find Math::BigInt::Foo, then
1252       Math::BigInt::Bar, and when this also fails, revert to
1253       Math::BigInt::Calc:
1254
1255               use Math::BigInt try => 'Foo,Math::BigInt::Bar';
1256
1257       The library that is loaded last will be used. Note that this can be
1258       overwritten at any time by loading a different library, and numbers
1259       constructed with different libraries cannot be used in math operations
1260       together.
1261
1262       What library to use?
1263
1264       Note: General purpose packages should not be explicit about the library
1265       to use; let the script author decide which is best.
1266
1267       Math::BigInt::GMP and Math::BigInt::Pari are in cases involving big
1268       numbers much faster than Calc, however it is slower when dealing with
1269       very small numbers (less than about 20 digits) and when converting very
1270       large numbers to decimal (for instance for printing, rounding,
1271       calculating their length in decimal etc).
1272
1273       So please select carefully what libary you want to use.
1274
1275       Different low-level libraries use different formats to store the
1276       numbers.  However, you should NOT depend on the number having a
1277       specific format internally.
1278
1279       See the respective math library module documentation for further
1280       details.
1281
1282   SIGN
1283       The sign is either '+', '-', 'NaN', '+inf' or '-inf'.
1284
1285       A sign of 'NaN' is used to represent the result when input arguments
1286       are not numbers or as a result of 0/0. '+inf' and '-inf' represent plus
1287       respectively minus infinity. You will get '+inf' when dividing a
1288       positive number by 0, and '-inf' when dividing any negative number by
1289       0.
1290
1291   mantissa(), exponent() and parts()
1292       "mantissa()" and "exponent()" return the said parts of the BigInt such
1293       that:
1294
1295               $m = $x->mantissa();
1296               $e = $x->exponent();
1297               $y = $m * ( 10 ** $e );
1298               print "ok\n" if $x == $y;
1299
1300       "($m,$e) = $x->parts()" is just a shortcut that gives you both of them
1301       in one go. Both the returned mantissa and exponent have a sign.
1302
1303       Currently, for BigInts $e is always 0, except +inf and -inf, where it
1304       is "+inf"; and for NaN, where it is "NaN"; and for "$x == 0", where it
1305       is 1 (to be compatible with Math::BigFloat's internal representation of
1306       a zero as 0E1).
1307
1308       $m is currently just a copy of the original number. The relation
1309       between $e and $m will stay always the same, though their real values
1310       might change.
1311

EXAMPLES

1313         use Math::BigInt;
1314
1315         sub bint { Math::BigInt->new(shift); }
1316
1317         $x = Math::BigInt->bstr("1234")       # string "1234"
1318         $x = "$x";                            # same as bstr()
1319         $x = Math::BigInt->bneg("1234");      # BigInt "-1234"
1320         $x = Math::BigInt->babs("-12345");    # BigInt "12345"
1321         $x = Math::BigInt->bnorm("-0.00");    # BigInt "0"
1322         $x = bint(1) + bint(2);               # BigInt "3"
1323         $x = bint(1) + "2";                   # ditto (auto-BigIntify of "2")
1324         $x = bint(1);                         # BigInt "1"
1325         $x = $x + 5 / 2;                      # BigInt "3"
1326         $x = $x ** 3;                         # BigInt "27"
1327         $x *= 2;                              # BigInt "54"
1328         $x = Math::BigInt->new(0);            # BigInt "0"
1329         $x--;                                 # BigInt "-1"
1330         $x = Math::BigInt->badd(4,5)          # BigInt "9"
1331         print $x->bsstr();                    # 9e+0
1332
1333       Examples for rounding:
1334
1335         use Math::BigFloat;
1336         use Test;
1337
1338         $x = Math::BigFloat->new(123.4567);
1339         $y = Math::BigFloat->new(123.456789);
1340         Math::BigFloat->accuracy(4);          # no more A than 4
1341
1342         ok ($x->copy()->fround(),123.4);      # even rounding
1343         print $x->copy()->fround(),"\n";      # 123.4
1344         Math::BigFloat->round_mode('odd');    # round to odd
1345         print $x->copy()->fround(),"\n";      # 123.5
1346         Math::BigFloat->accuracy(5);          # no more A than 5
1347         Math::BigFloat->round_mode('odd');    # round to odd
1348         print $x->copy()->fround(),"\n";      # 123.46
1349         $y = $x->copy()->fround(4),"\n";      # A = 4: 123.4
1350         print "$y, ",$y->accuracy(),"\n";     # 123.4, 4
1351
1352         Math::BigFloat->accuracy(undef);      # A not important now
1353         Math::BigFloat->precision(2);         # P important
1354         print $x->copy()->bnorm(),"\n";       # 123.46
1355         print $x->copy()->fround(),"\n";      # 123.46
1356
1357       Examples for converting:
1358
1359         my $x = Math::BigInt->new('0b1'.'01' x 123);
1360         print "bin: ",$x->as_bin()," hex:",$x->as_hex()," dec: ",$x,"\n";
1361

Autocreating constants

1363       After "use Math::BigInt ':constant'" all the integer decimal,
1364       hexadecimal and binary constants in the given scope are converted to
1365       "Math::BigInt".  This conversion happens at compile time.
1366
1367       In particular,
1368
1369         perl -MMath::BigInt=:constant -e 'print 2**100,"\n"'
1370
1371       prints the integer value of "2**100". Note that without conversion of
1372       constants the expression 2**100 will be calculated as perl scalar.
1373
1374       Please note that strings and floating point constants are not affected,
1375       so that
1376
1377               use Math::BigInt qw/:constant/;
1378
1379               $x = 1234567890123456789012345678901234567890
1380                       + 123456789123456789;
1381               $y = '1234567890123456789012345678901234567890'
1382                       + '123456789123456789';
1383
1384       do not work. You need an explicit Math::BigInt->new() around one of the
1385       operands. You should also quote large constants to protect loss of
1386       precision:
1387
1388               use Math::BigInt;
1389
1390               $x = Math::BigInt->new('1234567889123456789123456789123456789');
1391
1392       Without the quotes Perl would convert the large number to a floating
1393       point constant at compile time and then hand the result to BigInt,
1394       which results in an truncated result or a NaN.
1395
1396       This also applies to integers that look like floating point constants:
1397
1398               use Math::BigInt ':constant';
1399
1400               print ref(123e2),"\n";
1401               print ref(123.2e2),"\n";
1402
1403       will print nothing but newlines. Use either bignum or Math::BigFloat to
1404       get this to work.
1405

PERFORMANCE

1407       Using the form $x += $y; etc over $x = $x + $y is faster, since a copy
1408       of $x must be made in the second case. For long numbers, the copy can
1409       eat up to 20% of the work (in the case of addition/subtraction, less
1410       for multiplication/division). If $y is very small compared to $x, the
1411       form $x += $y is MUCH faster than $x = $x + $y since making the copy of
1412       $x takes more time then the actual addition.
1413
1414       With a technique called copy-on-write, the cost of copying with
1415       overload could be minimized or even completely avoided. A test
1416       implementation of COW did show performance gains for overloaded math,
1417       but introduced a performance loss due to a constant overhead for all
1418       other operations. So Math::BigInt does currently not COW.
1419
1420       The rewritten version of this module (vs. v0.01) is slower on certain
1421       operations, like "new()", "bstr()" and "numify()". The reason are that
1422       it does now more work and handles much more cases. The time spent in
1423       these operations is usually gained in the other math operations so that
1424       code on the average should get (much) faster. If they don't, please
1425       contact the author.
1426
1427       Some operations may be slower for small numbers, but are significantly
1428       faster for big numbers. Other operations are now constant (O(1), like
1429       "bneg()", "babs()" etc), instead of O(N) and thus nearly always take
1430       much less time.  These optimizations were done on purpose.
1431
1432       If you find the Calc module to slow, try to install any of the
1433       replacement modules and see if they help you.
1434
1435   Alternative math libraries
1436       You can use an alternative library to drive Math::BigInt. See the
1437       section "MATH LIBRARY" for more information.
1438
1439       For more benchmark results see
1440       <http://bloodgate.com/perl/benchmarks.html>.
1441
1442   SUBCLASSING

Subclassing Math::BigInt

1444       The basic design of Math::BigInt allows simple subclasses with very
1445       little work, as long as a few simple rules are followed:
1446
1447       · The public API must remain consistent, i.e. if a sub-class is
1448         overloading addition, the sub-class must use the same name, in this
1449         case badd(). The reason for this is that Math::BigInt is optimized to
1450         call the object methods directly.
1451
1452       · The private object hash keys like "$x-"{sign}> may not be changed,
1453         but additional keys can be added, like "$x-"{_custom}>.
1454
1455       · Accessor functions are available for all existing object hash keys
1456         and should be used instead of directly accessing the internal hash
1457         keys. The reason for this is that Math::BigInt itself has a pluggable
1458         interface which permits it to support different storage methods.
1459
1460       More complex sub-classes may have to replicate more of the logic
1461       internal of Math::BigInt if they need to change more basic behaviors. A
1462       subclass that needs to merely change the output only needs to overload
1463       "bstr()".
1464
1465       All other object methods and overloaded functions can be directly
1466       inherited from the parent class.
1467
1468       At the very minimum, any subclass will need to provide its own "new()"
1469       and can store additional hash keys in the object. There are also some
1470       package globals that must be defined, e.g.:
1471
1472         # Globals
1473         $accuracy = undef;
1474         $precision = -2;       # round to 2 decimal places
1475         $round_mode = 'even';
1476         $div_scale = 40;
1477
1478       Additionally, you might want to provide the following two globals to
1479       allow auto-upgrading and auto-downgrading to work correctly:
1480
1481         $upgrade = undef;
1482         $downgrade = undef;
1483
1484       This allows Math::BigInt to correctly retrieve package globals from the
1485       subclass, like $SubClass::precision.  See t/Math/BigInt/Subclass.pm or
1486       t/Math/BigFloat/SubClass.pm completely functional subclass examples.
1487
1488       Don't forget to
1489
1490               use overload;
1491
1492       in your subclass to automatically inherit the overloading from the
1493       parent. If you like, you can change part of the overloading, look at
1494       Math::String for an example.
1495

UPGRADING

1497       When used like this:
1498
1499               use Math::BigInt upgrade => 'Foo::Bar';
1500
1501       certain operations will 'upgrade' their calculation and thus the result
1502       to the class Foo::Bar. Usually this is used in conjunction with
1503       Math::BigFloat:
1504
1505               use Math::BigInt upgrade => 'Math::BigFloat';
1506
1507       As a shortcut, you can use the module "bignum":
1508
1509               use bignum;
1510
1511       Also good for oneliners:
1512
1513               perl -Mbignum -le 'print 2 ** 255'
1514
1515       This makes it possible to mix arguments of different classes (as in 2.5
1516       + 2) as well es preserve accuracy (as in sqrt(3)).
1517
1518       Beware: This feature is not fully implemented yet.
1519
1520   Auto-upgrade
1521       The following methods upgrade themselves unconditionally; that is if
1522       upgrade is in effect, they will always hand up their work:
1523
1524       bsqrt()
1525       div()
1526       blog()
1527       bexp()
1528
1529       Beware: This list is not complete.
1530
1531       All other methods upgrade themselves only when one (or all) of their
1532       arguments are of the class mentioned in $upgrade (This might change in
1533       later versions to a more sophisticated scheme):
1534

EXPORTS

1536       "Math::BigInt" exports nothing by default, but can export the following
1537       methods:
1538
1539               bgcd
1540               blcm
1541

CAVEATS

1543       Some things might not work as you expect them. Below is documented what
1544       is known to be troublesome:
1545
1546       bstr(), bsstr() and 'cmp'
1547        Both "bstr()" and "bsstr()" as well as automated stringify via
1548        overload now drop the leading '+'. The old code would return '+3', the
1549        new returns '3'.  This is to be consistent with Perl and to make "cmp"
1550        (especially with overloading) to work as you expect. It also solves
1551        problems with "Test.pm", because its "ok()" uses 'eq' internally.
1552
1553        Mark Biggar said, when asked about to drop the '+' altogether, or make
1554        only "cmp" work:
1555
1556                I agree (with the first alternative), don't add the '+' on positive
1557                numbers.  It's not as important anymore with the new internal
1558                form for numbers.  It made doing things like abs and neg easier,
1559                but those have to be done differently now anyway.
1560
1561        So, the following examples will now work all as expected:
1562
1563                use Test;
1564                BEGIN { plan tests => 1 }
1565                use Math::BigInt;
1566
1567                my $x = new Math::BigInt 3*3;
1568                my $y = new Math::BigInt 3*3;
1569
1570                ok ($x,3*3);
1571                print "$x eq 9" if $x eq $y;
1572                print "$x eq 9" if $x eq '9';
1573                print "$x eq 9" if $x eq 3*3;
1574
1575        Additionally, the following still works:
1576
1577                print "$x == 9" if $x == $y;
1578                print "$x == 9" if $x == 9;
1579                print "$x == 9" if $x == 3*3;
1580
1581        There is now a "bsstr()" method to get the string in scientific
1582        notation aka 1e+2 instead of 100. Be advised that overloaded 'eq'
1583        always uses bstr() for comparison, but Perl will represent some
1584        numbers as 100 and others as 1e+308. If in doubt, convert both
1585        arguments to Math::BigInt before comparing them as strings:
1586
1587                use Test;
1588                BEGIN { plan tests => 3 }
1589                use Math::BigInt;
1590
1591                $x = Math::BigInt->new('1e56'); $y = 1e56;
1592                ok ($x,$y);                     # will fail
1593                ok ($x->bsstr(),$y);            # okay
1594                $y = Math::BigInt->new($y);
1595                ok ($x,$y);                     # okay
1596
1597        Alternatively, simple use "<=>" for comparisons, this will get it
1598        always right. There is not yet a way to get a number automatically
1599        represented as a string that matches exactly the way Perl represents
1600        it.
1601
1602        See also the section about "Infinity and Not a Number" for problems in
1603        comparing NaNs.
1604
1605       int()
1606        "int()" will return (at least for Perl v5.7.1 and up) another BigInt,
1607        not a Perl scalar:
1608
1609                $x = Math::BigInt->new(123);
1610                $y = int($x);                           # BigInt 123
1611                $x = Math::BigFloat->new(123.45);
1612                $y = int($x);                           # BigInt 123
1613
1614        In all Perl versions you can use "as_number()" or "as_int" for the
1615        same effect:
1616
1617                $x = Math::BigFloat->new(123.45);
1618                $y = $x->as_number();                   # BigInt 123
1619                $y = $x->as_int();                      # ditto
1620
1621        This also works for other subclasses, like Math::String.
1622
1623        If you want a real Perl scalar, use "numify()":
1624
1625                $y = $x->numify();                      # 123 as scalar
1626
1627        This is seldom necessary, though, because this is done automatically,
1628        like when you access an array:
1629
1630                $z = $array[$x];                        # does work automatically
1631
1632       length
1633        The following will probably not do what you expect:
1634
1635                $c = Math::BigInt->new(123);
1636                print $c->length(),"\n";                # prints 30
1637
1638        It prints both the number of digits in the number and in the fraction
1639        part since print calls "length()" in list context. Use something like:
1640
1641                print scalar $c->length(),"\n";         # prints 3
1642
1643       bdiv
1644        The following will probably not do what you expect:
1645
1646                print $c->bdiv(10000),"\n";
1647
1648        It prints both quotient and remainder since print calls "bdiv()" in
1649        list context. Also, "bdiv()" will modify $c, so be careful. You
1650        probably want to use
1651
1652                print $c / 10000,"\n";
1653                print scalar $c->bdiv(10000),"\n";  # or if you want to modify $c
1654
1655        instead.
1656
1657        The quotient is always the greatest integer less than or equal to the
1658        real-valued quotient of the two operands, and the remainder (when it
1659        is nonzero) always has the same sign as the second operand; so, for
1660        example,
1661
1662                  1 / 4  => ( 0, 1)
1663                  1 / -4 => (-1,-3)
1664                 -3 / 4  => (-1, 1)
1665                 -3 / -4 => ( 0,-3)
1666                -11 / 2  => (-5,1)
1667                 11 /-2  => (-5,-1)
1668
1669        As a consequence, the behavior of the operator % agrees with the
1670        behavior of Perl's built-in % operator (as documented in the perlop
1671        manpage), and the equation
1672
1673                $x == ($x / $y) * $y + ($x % $y)
1674
1675        holds true for any $x and $y, which justifies calling the two return
1676        values of bdiv() the quotient and remainder. The only exception to
1677        this rule are when $y == 0 and $x is negative, then the remainder will
1678        also be negative. See below under "infinity handling" for the
1679        reasoning behind this.
1680
1681        Perl's 'use integer;' changes the behaviour of % and / for scalars,
1682        but will not change BigInt's way to do things. This is because under
1683        'use integer' Perl will do what the underlying C thinks is right and
1684        this is different for each system. If you need BigInt's behaving
1685        exactly like Perl's 'use integer', bug the author to implement it ;)
1686
1687       infinity handling
1688        Here are some examples that explain the reasons why certain results
1689        occur while handling infinity:
1690
1691        The following table shows the result of the division and the
1692        remainder, so that the equation above holds true. Some "ordinary"
1693        cases are strewn in to show more clearly the reasoning:
1694
1695                A /  B  =   C,     R so that C *    B +    R =    A
1696             =========================================================
1697                5 /   8 =   0,     5         0 *    8 +    5 =    5
1698                0 /   8 =   0,     0         0 *    8 +    0 =    0
1699                0 / inf =   0,     0         0 *  inf +    0 =    0
1700                0 /-inf =   0,     0         0 * -inf +    0 =    0
1701                5 / inf =   0,     5         0 *  inf +    5 =    5
1702                5 /-inf =   0,     5         0 * -inf +    5 =    5
1703                -5/ inf =   0,    -5         0 *  inf +   -5 =   -5
1704                -5/-inf =   0,    -5         0 * -inf +   -5 =   -5
1705               inf/   5 =  inf,    0       inf *    5 +    0 =  inf
1706              -inf/   5 = -inf,    0      -inf *    5 +    0 = -inf
1707               inf/  -5 = -inf,    0      -inf *   -5 +    0 =  inf
1708              -inf/  -5 =  inf,    0       inf *   -5 +    0 = -inf
1709                 5/   5 =    1,    0         1 *    5 +    0 =    5
1710                -5/  -5 =    1,    0         1 *   -5 +    0 =   -5
1711               inf/ inf =    1,    0         1 *  inf +    0 =  inf
1712              -inf/-inf =    1,    0         1 * -inf +    0 = -inf
1713               inf/-inf =   -1,    0        -1 * -inf +    0 =  inf
1714              -inf/ inf =   -1,    0         1 * -inf +    0 = -inf
1715                 8/   0 =  inf,    8       inf *    0 +    8 =    8
1716               inf/   0 =  inf,  inf       inf *    0 +  inf =  inf
1717                 0/   0 =  NaN
1718
1719        These cases below violate the "remainder has the sign of the second of
1720        the two arguments", since they wouldn't match up otherwise.
1721
1722                A /  B  =   C,     R so that C *    B +    R =    A
1723             ========================================================
1724              -inf/   0 = -inf, -inf      -inf *    0 +  inf = -inf
1725                -8/   0 = -inf,   -8      -inf *    0 +    8 = -8
1726
1727       Modifying and =
1728        Beware of:
1729
1730                $x = Math::BigFloat->new(5);
1731                $y = $x;
1732
1733        It will not do what you think, e.g. making a copy of $x. Instead it
1734        just makes a second reference to the same object and stores it in $y.
1735        Thus anything that modifies $x (except overloaded operators) will
1736        modify $y, and vice versa.  Or in other words, "=" is only safe if you
1737        modify your BigInts only via overloaded math. As soon as you use a
1738        method call it breaks:
1739
1740                $x->bmul(2);
1741                print "$x, $y\n";       # prints '10, 10'
1742
1743        If you want a true copy of $x, use:
1744
1745                $y = $x->copy();
1746
1747        You can also chain the calls like this, this will make first a copy
1748        and then multiply it by 2:
1749
1750                $y = $x->copy()->bmul(2);
1751
1752        See also the documentation for overload.pm regarding "=".
1753
1754       bpow
1755        "bpow()" (and the rounding functions) now modifies the first argument
1756        and returns it, unlike the old code which left it alone and only
1757        returned the result. This is to be consistent with "badd()" etc. The
1758        first three will modify $x, the last one won't:
1759
1760                print bpow($x,$i),"\n";         # modify $x
1761                print $x->bpow($i),"\n";        # ditto
1762                print $x **= $i,"\n";           # the same
1763                print $x ** $i,"\n";            # leave $x alone
1764
1765        The form "$x **= $y" is faster than "$x = $x ** $y;", though.
1766
1767       Overloading -$x
1768        The following:
1769
1770                $x = -$x;
1771
1772        is slower than
1773
1774                $x->bneg();
1775
1776        since overload calls "sub($x,0,1);" instead of "neg($x)". The first
1777        variant needs to preserve $x since it does not know that it later will
1778        get overwritten.  This makes a copy of $x and takes O(N), but
1779        $x->bneg() is O(1).
1780
1781       Mixing different object types
1782        In Perl you will get a floating point value if you do one of the
1783        following:
1784
1785                $float = 5.0 + 2;
1786                $float = 2 + 5.0;
1787                $float = 5 / 2;
1788
1789        With overloaded math, only the first two variants will result in a
1790        BigFloat:
1791
1792                use Math::BigInt;
1793                use Math::BigFloat;
1794
1795                $mbf = Math::BigFloat->new(5);
1796                $mbi2 = Math::BigInteger->new(5);
1797                $mbi = Math::BigInteger->new(2);
1798
1799                                                # what actually gets called:
1800                $float = $mbf + $mbi;           # $mbf->badd()
1801                $float = $mbf / $mbi;           # $mbf->bdiv()
1802                $integer = $mbi + $mbf;         # $mbi->badd()
1803                $integer = $mbi2 / $mbi;        # $mbi2->bdiv()
1804                $integer = $mbi2 / $mbf;        # $mbi2->bdiv()
1805
1806        This is because math with overloaded operators follows the first
1807        (dominating) operand, and the operation of that is called and returns
1808        thus the result. So, Math::BigInt::bdiv() will always return a
1809        Math::BigInt, regardless whether the result should be a Math::BigFloat
1810        or the second operant is one.
1811
1812        To get a Math::BigFloat you either need to call the operation
1813        manually, make sure the operands are already of the proper type or
1814        casted to that type via Math::BigFloat->new():
1815
1816                $float = Math::BigFloat->new($mbi2) / $mbi;     # = 2.5
1817
1818        Beware of simple "casting" the entire expression, this would only
1819        convert the already computed result:
1820
1821                $float = Math::BigFloat->new($mbi2 / $mbi);     # = 2.0 thus wrong!
1822
1823        Beware also of the order of more complicated expressions like:
1824
1825                $integer = ($mbi2 + $mbi) / $mbf;               # int / float => int
1826                $integer = $mbi2 / Math::BigFloat->new($mbi);   # ditto
1827
1828        If in doubt, break the expression into simpler terms, or cast all
1829        operands to the desired resulting type.
1830
1831        Scalar values are a bit different, since:
1832
1833                $float = 2 + $mbf;
1834                $float = $mbf + 2;
1835
1836        will both result in the proper type due to the way the overloaded math
1837        works.
1838
1839        This section also applies to other overloaded math packages, like
1840        Math::String.
1841
1842        One solution to you problem might be autoupgrading|upgrading. See the
1843        pragmas bignum, bigint and bigrat for an easy way to do this.
1844
1845       bsqrt()
1846        "bsqrt()" works only good if the result is a big integer, e.g. the
1847        square root of 144 is 12, but from 12 the square root is 3, regardless
1848        of rounding mode. The reason is that the result is always truncated to
1849        an integer.
1850
1851        If you want a better approximation of the square root, then use:
1852
1853                $x = Math::BigFloat->new(12);
1854                Math::BigFloat->precision(0);
1855                Math::BigFloat->round_mode('even');
1856                print $x->copy->bsqrt(),"\n";           # 4
1857
1858                Math::BigFloat->precision(2);
1859                print $x->bsqrt(),"\n";                 # 3.46
1860                print $x->bsqrt(3),"\n";                # 3.464
1861
1862       brsft()
1863        For negative numbers in base see also brsft.
1864

LICENSE

1866       This program is free software; you may redistribute it and/or modify it
1867       under the same terms as Perl itself.
1868

SEE ALSO

1870       Math::BigFloat, Math::BigRat and Math::Big as well as
1871       Math::BigInt::BitVect, Math::BigInt::Pari and  Math::BigInt::GMP.
1872
1873       The pragmas bignum, bigint and bigrat also might be of interest because
1874       they solve the autoupgrading/downgrading issue, at least partly.
1875
1876       The package at
1877       <http://search.cpan.org/search?mode=module&query=Math%3A%3ABigInt>
1878       contains more documentation including a full version history,
1879       testcases, empty subclass files and benchmarks.
1880

AUTHORS

1882       Original code by Mark Biggar, overloaded interface by Ilya Zakharevich.
1883       Completely rewritten by Tels http://bloodgate.com in late 2000, 2001 -
1884       2006 and still at it in 2007.
1885
1886       Many people contributed in one or more ways to the final beast, see the
1887       file CREDITS for an (incomplete) list. If you miss your name, please
1888       drop me a mail. Thank you!
1889
1890
1891
1892perl v5.12.4                      2011-06-20                 Math::BigInt(3pm)
Impressum