3 # The following hash values are used:
4 # value: unsigned int with actual value (as a Math::BigInt::Calc or similiar)
5 # sign : +,-,NaN,+inf,-inf
8 # _f : flags, used by MBF to flag parts of a float as untouchable
10 # Remember not to take shortcuts ala $xs = $x->{value}; $CALC->foo($xs); since
11 # underlying lib might change the reference!
14 my $class = "Math::BigInt";
19 @ISA = qw( Exporter );
20 @EXPORT_OK = qw( objectify _swap bgcd blcm);
21 use vars qw/$round_mode $accuracy $precision $div_scale $rnd_mode/;
24 # Inside overload, the first arg is always an object. If the original code had
25 # it reversed (like $x = 2 * $y), then the third paramater indicates this
26 # swapping. To make it work, we use a helper routine which not only reswaps the
27 # params, but also makes a new object in this case. See _swap() for details,
28 # especially the cases of operators with different classes.
30 # For overloaded ops with only one argument we simple use $_[0]->copy() to
31 # preserve the argument.
33 # Thus inheritance of overload operators becomes possible and transparent for
34 # our subclasses without the need to repeat the entire overload section there.
37 '=' => sub { $_[0]->copy(); },
39 # '+' and '-' do not use _swap, since it is a triffle slower. If you want to
40 # override _swap (if ever), then override overload of '+' and '-', too!
41 # for sub it is a bit tricky to keep b: b-a => -a+b
42 '-' => sub { my $c = $_[0]->copy; $_[2] ?
43 $c->bneg()->badd($_[1]) :
45 '+' => sub { $_[0]->copy()->badd($_[1]); },
47 # some shortcuts for speed (assumes that reversed order of arguments is routed
48 # to normal '+' and we thus can always modify first arg. If this is changed,
49 # this breaks and must be adjusted.)
50 '+=' => sub { $_[0]->badd($_[1]); },
51 '-=' => sub { $_[0]->bsub($_[1]); },
52 '*=' => sub { $_[0]->bmul($_[1]); },
53 '/=' => sub { scalar $_[0]->bdiv($_[1]); },
54 '%=' => sub { $_[0]->bmod($_[1]); },
55 '^=' => sub { $_[0]->bxor($_[1]); },
56 '&=' => sub { $_[0]->band($_[1]); },
57 '|=' => sub { $_[0]->bior($_[1]); },
58 '**=' => sub { $_[0]->bpow($_[1]); },
60 '..' => \&_pointpoint,
62 '<=>' => sub { $_[2] ?
63 ref($_[0])->bcmp($_[1],$_[0]) :
64 ref($_[0])->bcmp($_[0],$_[1])},
67 $_[1] cmp $_[0]->bstr() :
68 $_[0]->bstr() cmp $_[1] },
70 'log' => sub { $_[0]->copy()->blog(); },
71 'int' => sub { $_[0]->copy(); },
72 'neg' => sub { $_[0]->copy()->bneg(); },
73 'abs' => sub { $_[0]->copy()->babs(); },
74 '~' => sub { $_[0]->copy()->bnot(); },
76 '*' => sub { my @a = ref($_[0])->_swap(@_); $a[0]->bmul($a[1]); },
77 '/' => sub { my @a = ref($_[0])->_swap(@_);scalar $a[0]->bdiv($a[1]);},
78 '%' => sub { my @a = ref($_[0])->_swap(@_); $a[0]->bmod($a[1]); },
79 '**' => sub { my @a = ref($_[0])->_swap(@_); $a[0]->bpow($a[1]); },
80 '<<' => sub { my @a = ref($_[0])->_swap(@_); $a[0]->blsft($a[1]); },
81 '>>' => sub { my @a = ref($_[0])->_swap(@_); $a[0]->brsft($a[1]); },
83 '&' => sub { my @a = ref($_[0])->_swap(@_); $a[0]->band($a[1]); },
84 '|' => sub { my @a = ref($_[0])->_swap(@_); $a[0]->bior($a[1]); },
85 '^' => sub { my @a = ref($_[0])->_swap(@_); $a[0]->bxor($a[1]); },
87 # can modify arg of ++ and --, so avoid a new-copy for speed, but don't
88 # use $_[0]->__one(), it modifies $_[0] to be 1!
89 '++' => sub { $_[0]->binc() },
90 '--' => sub { $_[0]->bdec() },
92 # if overloaded, O(1) instead of O(N) and twice as fast for small numbers
94 # this kludge is needed for perl prior 5.6.0 since returning 0 here fails :-/
95 # v5.6.1 dumps on that: return !$_[0]->is_zero() || undef; :-(
96 my $t = !$_[0]->is_zero();
101 # the original qw() does not work with the TIESCALAR below, why?
102 # Order of arguments unsignificant
103 '""' => sub { $_[0]->bstr(); },
104 '0+' => sub { $_[0]->numify(); }
107 ##############################################################################
108 # global constants, flags and accessory
110 use constant MB_NEVER_ROUND => 0x0001;
112 my $NaNOK=1; # are NaNs ok?
113 my $nan = 'NaN'; # constants for easier life
115 my $CALC = 'Math::BigInt::Calc'; # module to do low level math
116 my $IMPORT = 0; # did import() yet?
117 sub _core_lib () { return $CALC; } # for test suite
119 $round_mode = 'even'; # one of 'even', 'odd', '+inf', '-inf', 'zero' or 'trunc'
124 ##############################################################################
125 # the old code had $rnd_mode, so we need to support it, too
128 sub TIESCALAR { my ($class) = @_; bless \$round_mode, $class; }
129 sub FETCH { return $round_mode; }
130 sub STORE { $rnd_mode = $_[0]->round_mode($_[1]); }
132 BEGIN { tie $rnd_mode, 'Math::BigInt'; }
134 ##############################################################################
139 # make Class->round_mode() work
141 my $class = ref($self) || $self || __PACKAGE__;
145 die "Unknown round mode $m"
146 if $m !~ /^(even|odd|\+inf|\-inf|zero|trunc)$/;
147 ${"${class}::round_mode"} = $m; return $m;
149 return ${"${class}::round_mode"};
155 # make Class->round_mode() work
157 my $class = ref($self) || $self || __PACKAGE__;
160 die ('div_scale must be greater than zero') if $_[0] < 0;
161 ${"${class}::div_scale"} = shift;
163 return ${"${class}::div_scale"};
168 # $x->accuracy($a); ref($x) $a
169 # $x->accuracy(); ref($x)
170 # Class->accuracy(); class
171 # Class->accuracy($a); class $a
174 my $class = ref($x) || $x || __PACKAGE__;
177 # need to set new value?
181 die ('accuracy must not be zero') if defined $a && $a == 0;
184 # $object->accuracy() or fallback to global
185 $x->bround($a) if defined $a;
186 $x->{_a} = $a; # set/overwrite, even if not rounded
187 $x->{_p} = undef; # clear P
192 ${"${class}::accuracy"} = $a;
194 return $a; # shortcut
199 # $object->accuracy() or fallback to global
200 return $x->{_a} || ${"${class}::accuracy"};
202 return ${"${class}::accuracy"};
207 # $x->precision($p); ref($x) $p
208 # $x->precision(); ref($x)
209 # Class->precision(); class
210 # Class->precision($p); class $p
213 my $class = ref($x) || $x || __PACKAGE__;
216 # need to set new value?
222 # $object->precision() or fallback to global
223 $x->bfround($p) if defined $p;
224 $x->{_p} = $p; # set/overwrite, even if not rounded
225 $x->{_a} = undef; # clear P
230 ${"${class}::precision"} = $p;
232 return $p; # shortcut
237 # $object->precision() or fallback to global
238 return $x->{_p} || ${"${class}::precision"};
240 return ${"${class}::precision"};
245 # select accuracy parameter based on precedence,
246 # used by bround() and bfround(), may return undef for scale (means no op)
247 my ($x,$s,$m,$scale,$mode) = @_;
248 $scale = $x->{_a} if !defined $scale;
249 $scale = $s if (!defined $scale);
250 $mode = $m if !defined $mode;
251 return ($scale,$mode);
256 # select precision parameter based on precedence,
257 # used by bround() and bfround(), may return undef for scale (means no op)
258 my ($x,$s,$m,$scale,$mode) = @_;
259 $scale = $x->{_p} if !defined $scale;
260 $scale = $s if (!defined $scale);
261 $mode = $m if !defined $mode;
262 return ($scale,$mode);
265 ##############################################################################
273 # if two arguments, the first one is the class to "swallow" subclasses
281 return unless ref($x); # only for objects
283 my $self = {}; bless $self,$c;
285 foreach my $k (keys %$x)
289 $self->{value} = $CALC->_copy($x->{value}); next;
291 if (!($r = ref($x->{$k})))
293 $self->{$k} = $x->{$k}; next;
297 $self->{$k} = \${$x->{$k}};
299 elsif ($r eq 'ARRAY')
301 $self->{$k} = [ @{$x->{$k}} ];
305 # only one level deep!
306 foreach my $h (keys %{$x->{$k}})
308 $self->{$k}->{$h} = $x->{$k}->{$h};
314 if ($xk->can('copy'))
316 $self->{$k} = $xk->copy();
320 $self->{$k} = $xk->new($xk);
329 # create a new BigInt object from a string or another BigInt object.
330 # see hash keys documented at top
332 # the argument could be an object, so avoid ||, && etc on it, this would
333 # cause costly overloaded code to be called. The only allowed ops are
336 my ($class,$wanted,$a,$p,$r) = @_;
338 # avoid numify-calls by not using || on $wanted!
339 return $class->bzero($a,$p) if !defined $wanted; # default to 0
340 return $class->copy($wanted,$a,$p,$r) if ref($wanted);
342 $class->import() if $IMPORT == 0; # make require work
344 my $self = {}; bless $self, $class;
345 # handle '+inf', '-inf' first
346 if ($wanted =~ /^[+-]?inf$/)
348 $self->{value} = $CALC->_zero();
349 $self->{sign} = $wanted; $self->{sign} = '+inf' if $self->{sign} eq 'inf';
352 # split str in m mantissa, e exponent, i integer, f fraction, v value, s sign
353 my ($mis,$miv,$mfv,$es,$ev) = _split(\$wanted);
356 die "$wanted is not a number initialized to $class" if !$NaNOK;
358 $self->{value} = $CALC->_zero();
359 $self->{sign} = $nan;
364 # _from_hex or _from_bin
365 $self->{value} = $mis->{value};
366 $self->{sign} = $mis->{sign};
367 return $self; # throw away $mis
369 # make integer from mantissa by adjusting exp, then convert to bigint
370 $self->{sign} = $$mis; # store sign
371 $self->{value} = $CALC->_zero(); # for all the NaN cases
372 my $e = int("$$es$$ev"); # exponent (avoid recursion)
375 my $diff = $e - CORE::length($$mfv);
376 if ($diff < 0) # Not integer
379 $self->{sign} = $nan;
383 # adjust fraction and add it to value
384 # print "diff > 0 $$miv\n";
385 $$miv = $$miv . ($$mfv . '0' x $diff);
390 if ($$mfv ne '') # e <= 0
392 # fraction and negative/zero E => NOI
393 #print "NOI 2 \$\$mfv '$$mfv'\n";
394 $self->{sign} = $nan;
398 # xE-y, and empty mfv
401 if ($$miv !~ s/0{$e}$//) # can strip so many zero's?
404 $self->{sign} = $nan;
408 $self->{sign} = '+' if $$miv eq '0'; # normalize -0 => +0
409 $self->{value} = $CALC->_new($miv) if $self->{sign} =~ /^[+-]$/;
410 # if any of the globals is set, use them to round and store them inside $self
411 # do not round for new($x,undef,undef) since that is used by MBF to signal
413 $self->round($a,$p,$r) unless @_ == 4 && !defined $a && !defined $p;
419 # create a bigint 'NaN', if given a BigInt, set it to 'NaN'
421 $self = $class if !defined $self;
424 my $c = $self; $self = {}; bless $self, $c;
426 $self->import() if $IMPORT == 0; # make require work
427 return if $self->modify('bnan');
428 $self->{value} = $CALC->_zero();
429 $self->{sign} = $nan;
430 delete $self->{_a}; delete $self->{_p}; # rounding NaN is silly
436 # create a bigint '+-inf', if given a BigInt, set it to '+-inf'
437 # the sign is either '+', or if given, used from there
439 my $sign = shift; $sign = '+' if !defined $sign || $sign ne '-';
440 $self = $class if !defined $self;
443 my $c = $self; $self = {}; bless $self, $c;
445 $self->import() if $IMPORT == 0; # make require work
446 return if $self->modify('binf');
447 $self->{value} = $CALC->_zero();
448 $self->{sign} = $sign.'inf';
449 ($self->{_a},$self->{_p}) = @_; # take over requested rounding
455 # create a bigint '+0', if given a BigInt, set it to 0
457 $self = $class if !defined $self;
461 my $c = $self; $self = {}; bless $self, $c;
463 $self->import() if $IMPORT == 0; # make require work
464 return if $self->modify('bzero');
465 $self->{value} = $CALC->_zero();
470 if (defined $self->{_a} && defined $_[0] && $_[0] > $self->{_a});
472 if (defined $self->{_p} && defined $_[1] && $_[1] < $self->{_p});
479 # create a bigint '+1' (or -1 if given sign '-'),
480 # if given a BigInt, set it to +1 or -1, respecively
482 my $sign = shift; $sign = '+' if !defined $sign || $sign ne '-';
483 $self = $class if !defined $self;
487 my $c = $self; $self = {}; bless $self, $c;
489 $self->import() if $IMPORT == 0; # make require work
490 return if $self->modify('bone');
491 $self->{value} = $CALC->_one();
492 $self->{sign} = $sign;
496 if (defined $self->{_a} && defined $_[0] && $_[0] > $self->{_a});
498 if (defined $self->{_p} && defined $_[1] && $_[1] < $self->{_p});
503 ##############################################################################
504 # string conversation
508 # (ref to BFLOAT or num_str ) return num_str
509 # Convert number from internal format to scientific string format.
510 # internal format is always normalized (no leading zeros, "-0E0" => "+0E0")
511 my $x = shift; $class = ref($x) || $x; $x = $class->new(shift) if !ref($x);
512 # my ($self,$x) = ref($_[0]) ? (ref($_[0]),$_[0]) : objectify(1,@_);
514 if ($x->{sign} !~ /^[+-]$/)
516 return $x->{sign} unless $x->{sign} eq '+inf'; # -inf, NaN
519 my ($m,$e) = $x->parts();
520 # e can only be positive
522 # MBF: my $s = $e->{sign}; $s = '' if $s eq '-'; my $sep = 'e'.$s;
523 return $m->bstr().$sign.$e->bstr();
528 # make a string from bigint object
529 my $x = shift; $class = ref($x) || $x; $x = $class->new(shift) if !ref($x);
530 # my ($self,$x) = ref($_[0]) ? (ref($_[0]),$_[0]) : objectify(1,@_);
532 if ($x->{sign} !~ /^[+-]$/)
534 return $x->{sign} unless $x->{sign} eq '+inf'; # -inf, NaN
537 my $es = ''; $es = $x->{sign} if $x->{sign} eq '-';
538 return $es.${$CALC->_str($x->{value})};
543 # Make a "normal" scalar from a BigInt object
544 my $x = shift; $x = $class->new($x) unless ref $x;
545 return $x->{sign} if $x->{sign} !~ /^[+-]$/;
546 my $num = $CALC->_num($x->{value});
547 return -$num if $x->{sign} eq '-';
551 ##############################################################################
552 # public stuff (usually prefixed with "b")
556 # return the sign of the number: +/-/NaN
557 my ($self,$x) = ref($_[0]) ? (ref($_[0]),$_[0]) : objectify(1,@_);
562 sub _find_round_parameters
564 # After any operation or when calling round(), the result is rounded by
565 # regarding the A & P from arguments, local parameters, or globals.
567 # This procedure finds the round parameters, but it is for speed reasons
568 # duplicated in round. Otherwise, it is tested by the testsuite and used
571 my ($self,$a,$p,$r,@args) = @_;
572 # $a accuracy, if given by caller
573 # $p precision, if given by caller
574 # $r round_mode, if given by caller
575 # @args all 'other' arguments (0 for unary, 1 for binary ops)
577 # leave bigfloat parts alone
578 return ($self) if exists $self->{_f} && $self->{_f} & MB_NEVER_ROUND != 0;
580 my $c = ref($self); # find out class of argument(s)
583 # now pick $a or $p, but only if we have got "arguments"
586 foreach ($self,@args)
588 # take the defined one, or if both defined, the one that is smaller
589 $a = $_->{_a} if (defined $_->{_a}) && (!defined $a || $_->{_a} < $a);
594 # even if $a is defined, take $p, to signal error for both defined
595 foreach ($self,@args)
597 # take the defined one, or if both defined, the one that is bigger
599 $p = $_->{_p} if (defined $_->{_p}) && (!defined $p || $_->{_p} > $p);
602 # if still none defined, use globals (#2)
603 $a = ${"$c\::accuracy"} unless defined $a;
604 $p = ${"$c\::precision"} unless defined $p;
607 return ($self) unless defined $a || defined $p; # early out
609 # set A and set P is an fatal error
610 return ($self->bnan()) if defined $a && defined $p;
612 $r = ${"$c\::round_mode"} unless defined $r;
613 die "Unknown round mode '$r'" if $r !~ /^(even|odd|\+inf|\-inf|zero|trunc)$/;
615 return ($self,$a,$p,$r);
620 # Round $self according to given parameters, or given second argument's
621 # parameters or global defaults
623 # for speed reasons, _find_round_parameters is embeded here:
625 my ($self,$a,$p,$r,@args) = @_;
626 # $a accuracy, if given by caller
627 # $p precision, if given by caller
628 # $r round_mode, if given by caller
629 # @args all 'other' arguments (0 for unary, 1 for binary ops)
631 # leave bigfloat parts alone
632 return ($self) if exists $self->{_f} && $self->{_f} & MB_NEVER_ROUND != 0;
634 my $c = ref($self); # find out class of argument(s)
637 # now pick $a or $p, but only if we have got "arguments"
640 foreach ($self,@args)
642 # take the defined one, or if both defined, the one that is smaller
643 $a = $_->{_a} if (defined $_->{_a}) && (!defined $a || $_->{_a} < $a);
648 # even if $a is defined, take $p, to signal error for both defined
649 foreach ($self,@args)
651 # take the defined one, or if both defined, the one that is bigger
653 $p = $_->{_p} if (defined $_->{_p}) && (!defined $p || $_->{_p} > $p);
656 # if still none defined, use globals (#2)
657 $a = ${"$c\::accuracy"} unless defined $a;
658 $p = ${"$c\::precision"} unless defined $p;
661 return $self unless defined $a || defined $p; # early out
663 # set A and set P is an fatal error
664 return $self->bnan() if defined $a && defined $p;
666 $r = ${"$c\::round_mode"} unless defined $r;
667 die "Unknown round mode '$r'" if $r !~ /^(even|odd|\+inf|\-inf|zero|trunc)$/;
669 # now round, by calling either fround or ffround:
672 $self->bround($a,$r) if !defined $self->{_a} || $self->{_a} >= $a;
674 else # both can't be undefined due to early out
676 $self->bfround($p,$r) if !defined $self->{_p} || $self->{_p} <= $p;
678 $self->bnorm(); # after round, normalize
683 # (numstr or BINT) return BINT
684 # Normalize number -- no-op here
685 my ($self,$x) = ref($_[0]) ? (ref($_[0]),$_[0]) : objectify(1,@_);
691 # (BINT or num_str) return BINT
692 # make number absolute, or return absolute BINT from string
693 my ($self,$x) = ref($_[0]) ? (ref($_[0]),$_[0]) : objectify(1,@_);
695 return $x if $x->modify('babs');
696 # post-normalized abs for internal use (does nothing for NaN)
697 $x->{sign} =~ s/^-/+/;
703 # (BINT or num_str) return BINT
704 # negate number or make a negated number from string
705 my ($self,$x) = ref($_[0]) ? (ref($_[0]),$_[0]) : objectify(1,@_);
707 return $x if $x->modify('bneg');
708 # for +0 dont negate (to have always normalized)
709 return $x if $x->is_zero();
710 $x->{sign} =~ tr/+-/-+/; # does nothing for NaN
716 # Compares 2 values. Returns one of undef, <0, =0, >0. (suitable for sort)
717 # (BINT or num_str, BINT or num_str) return cond_code
718 my ($self,$x,$y) = objectify(2,@_);
720 if (($x->{sign} !~ /^[+-]$/) || ($y->{sign} !~ /^[+-]$/))
722 # handle +-inf and NaN
723 return undef if (($x->{sign} eq $nan) || ($y->{sign} eq $nan));
724 return 0 if $x->{sign} eq $y->{sign} && $x->{sign} =~ /^[+-]inf$/;
725 return +1 if $x->{sign} eq '+inf';
726 return -1 if $x->{sign} eq '-inf';
727 return -1 if $y->{sign} eq '+inf';
728 return +1 if $y->{sign} eq '-inf';
730 # check sign for speed first
731 return 1 if $x->{sign} eq '+' && $y->{sign} eq '-'; # does also 0 <=> -y
732 return -1 if $x->{sign} eq '-' && $y->{sign} eq '+'; # does also -x <=> 0
735 my $xz = $x->is_zero();
736 my $yz = $y->is_zero();
737 return 0 if $xz && $yz; # 0 <=> 0
738 return -1 if $xz && $y->{sign} eq '+'; # 0 <=> +y
739 return 1 if $yz && $x->{sign} eq '+'; # +x <=> 0
741 # post-normalized compare for internal use (honors signs)
742 if ($x->{sign} eq '+')
744 return 1 if $y->{sign} eq '-'; # 0 check handled above
745 return $CALC->_acmp($x->{value},$y->{value});
749 return -1 if $y->{sign} eq '+';
750 return $CALC->_acmp($y->{value},$x->{value}); # swaped
752 # &cmp($x->{value},$y->{value},$x->{sign},$y->{sign}) <=> 0;
757 # Compares 2 values, ignoring their signs.
758 # Returns one of undef, <0, =0, >0. (suitable for sort)
759 # (BINT, BINT) return cond_code
760 my ($self,$x,$y) = objectify(2,@_);
762 if (($x->{sign} !~ /^[+-]$/) || ($y->{sign} !~ /^[+-]$/))
764 # handle +-inf and NaN
765 return undef if (($x->{sign} eq $nan) || ($y->{sign} eq $nan));
766 return 0 if $x->{sign} =~ /^[+-]inf$/ && $y->{sign} =~ /^[+-]inf$/;
767 return +1; # inf is always bigger
769 $CALC->_acmp($x->{value},$y->{value}) <=> 0;
774 # add second arg (BINT or string) to first (BINT) (modifies first)
775 # return result as BINT
776 my ($self,$x,$y,@r) = objectify(2,@_);
778 return $x if $x->modify('badd');
780 $r[3] = $y; # no push!
781 # inf and NaN handling
782 if (($x->{sign} !~ /^[+-]$/) || ($y->{sign} !~ /^[+-]$/))
785 return $x->bnan() if (($x->{sign} eq $nan) || ($y->{sign} eq $nan));
787 if (($x->{sign} =~ /^[+-]inf$/) && ($y->{sign} =~ /^[+-]inf$/))
789 # + and + => +, - and - => -, + and - => 0, - and + => 0
790 return $x->bzero(@r) if $x->{sign} ne $y->{sign};
793 # +-inf + something => +inf
794 # something +-inf => +-inf
795 $x->{sign} = $y->{sign}, return $x if $y->{sign} =~ /^[+-]inf$/;
799 # speed: no add for 0+y or x+0
800 return $x->round(@r) if $y->is_zero(); # x+0
801 if ($x->is_zero()) # 0+y
803 # make copy, clobbering up x
804 $x->{value} = $CALC->_copy($y->{value});
805 $x->{sign} = $y->{sign} || $nan;
806 return $x->round(@r);
809 my ($sx, $sy) = ( $x->{sign}, $y->{sign} ); # get signs
813 $x->{value} = $CALC->_add($x->{value},$y->{value}); # same sign, abs add
818 my $a = $CALC->_acmp ($y->{value},$x->{value}); # absolute compare
821 #print "swapped sub (a=$a)\n";
822 $x->{value} = $CALC->_sub($y->{value},$x->{value},1); # abs sub w/ swap
827 # speedup, if equal, set result to 0
828 #print "equal sub, result = 0\n";
829 $x->{value} = $CALC->_zero();
834 #print "unswapped sub (a=$a)\n";
835 $x->{value} = $CALC->_sub($x->{value}, $y->{value}); # abs sub
844 # (BINT or num_str, BINT or num_str) return num_str
845 # subtract second arg from first, modify first
846 my ($self,$x,$y,$a,$p,$r) = objectify(2,@_);
848 return $x if $x->modify('bsub');
850 if (!$y->is_zero()) # don't need to do anything if $y is 0
852 $y->{sign} =~ tr/+\-/-+/; # does nothing for NaN
853 $x->badd($y,$a,$p,$r); # badd does not leave internal zeros
854 $y->{sign} =~ tr/+\-/-+/; # refix $y (does nothing for NaN)
856 $x; # already rounded by badd() or no round necc.
861 # increment arg by one
862 my ($self,$x,$a,$p,$r) = ref($_[0]) ? (ref($_[0]),@_) : objectify(1,@_);
863 return $x if $x->modify('binc');
865 if ($x->{sign} eq '+')
867 $x->{value} = $CALC->_inc($x->{value});
868 return $x->round($a,$p,$r);
870 elsif ($x->{sign} eq '-')
872 $x->{value} = $CALC->_dec($x->{value});
873 $x->{sign} = '+' if $CALC->_is_zero($x->{value}); # -1 +1 => -0 => +0
874 return $x->round($a,$p,$r);
876 # inf, nan handling etc
877 $x->badd($self->__one(),$a,$p,$r); # badd does round
882 # decrement arg by one
883 my ($self,$x,$a,$p,$r) = ref($_[0]) ? (ref($_[0]),@_) : objectify(1,@_);
884 return $x if $x->modify('bdec');
886 my $zero = $CALC->_is_zero($x->{value}) && $x->{sign} eq '+';
888 if (($x->{sign} eq '-') || $zero)
890 $x->{value} = $CALC->_inc($x->{value});
891 $x->{sign} = '-' if $zero; # 0 => 1 => -1
892 $x->{sign} = '+' if $CALC->_is_zero($x->{value}); # -1 +1 => -0 => +0
893 return $x->round($a,$p,$r);
896 elsif ($x->{sign} eq '+')
898 $x->{value} = $CALC->_dec($x->{value});
899 return $x->round($a,$p,$r);
901 # inf, nan handling etc
902 $x->badd($self->__one('-'),$a,$p,$r); # badd does round
907 # not implemented yet
908 my ($self,$x,$a,$p,$r) = ref($_[0]) ? (ref($_[0]),@_) : objectify(1,@_);
915 # (BINT or num_str, BINT or num_str) return BINT
916 # does not modify arguments, but returns new object
917 # Lowest Common Multiplicator
919 my $y = shift; my ($x);
926 $x = $class->new($y);
928 while (@_) { $x = __lcm($x,shift); }
934 # (BINT or num_str, BINT or num_str) return BINT
935 # does not modify arguments, but returns new object
936 # GCD -- Euclids algorithm, variant C (Knuth Vol 3, pg 341 ff)
939 $y = __PACKAGE__->new($y) if !ref($y);
941 my $x = $y->copy(); # keep arguments
942 if ($CALC->can('_gcd'))
946 $y = shift; $y = $self->new($y) if !ref($y);
947 next if $y->is_zero();
948 return $x->bnan() if $y->{sign} !~ /^[+-]$/; # y NaN?
949 $x->{value} = $CALC->_gcd($x->{value},$y->{value}); last if $x->is_one();
956 $y = shift; $y = $self->new($y) if !ref($y);
957 $x = __gcd($x,$y->copy()); last if $x->is_one(); # _gcd handles NaN
965 # (num_str or BINT) return BINT
966 # represent ~x as twos-complement number
967 # we don't need $self, so undef instead of ref($_[0]) make it slightly faster
968 my ($self,$x,$a,$p,$r) = ref($_[0]) ? (undef,@_) : objectify(1,@_);
970 return $x if $x->modify('bnot');
971 $x->bneg()->bdec(); # bdec already does round
976 # return true if arg (BINT or num_str) is zero (array '+', '0')
977 # we don't need $self, so undef instead of ref($_[0]) make it slightly faster
978 my ($self,$x) = ref($_[0]) ? (undef,$_[0]) : objectify(1,@_);
980 return 0 if $x->{sign} !~ /^\+$/; # -, NaN & +-inf aren't
981 $CALC->_is_zero($x->{value});
986 # return true if arg (BINT or num_str) is NaN
987 my ($self,$x) = ref($_[0]) ? (ref($_[0]),$_[0]) : objectify(1,@_);
989 return 1 if $x->{sign} eq $nan;
995 # return true if arg (BINT or num_str) is +-inf
996 my ($self,$x,$sign) = ref($_[0]) ? (ref($_[0]),@_) : objectify(1,@_);
998 $sign = '' if !defined $sign;
999 return 0 if $sign !~ /^([+-]|)$/;
1003 return 1 if ($x->{sign} =~ /^[+-]inf$/);
1006 $sign = quotemeta($sign.'inf');
1007 return 1 if ($x->{sign} =~ /^$sign$/);
1013 # return true if arg (BINT or num_str) is +1
1014 # or -1 if sign is given
1015 # we don't need $self, so undef instead of ref($_[0]) make it slightly faster
1016 my ($self,$x,$sign) = ref($_[0]) ? (undef,@_) : objectify(1,@_);
1018 $sign = '' if !defined $sign; $sign = '+' if $sign ne '-';
1020 return 0 if $x->{sign} ne $sign; # -1 != +1, NaN, +-inf aren't either
1021 $CALC->_is_one($x->{value});
1026 # return true when arg (BINT or num_str) is odd, false for even
1027 # we don't need $self, so undef instead of ref($_[0]) make it slightly faster
1028 my ($self,$x) = ref($_[0]) ? (undef,$_[0]) : objectify(1,@_);
1030 return 0 if $x->{sign} !~ /^[+-]$/; # NaN & +-inf aren't
1031 $CALC->_is_odd($x->{value});
1036 # return true when arg (BINT or num_str) is even, false for odd
1037 # we don't need $self, so undef instead of ref($_[0]) make it slightly faster
1038 my ($self,$x) = ref($_[0]) ? (undef,$_[0]) : objectify(1,@_);
1040 return 0 if $x->{sign} !~ /^[+-]$/; # NaN & +-inf aren't
1041 $CALC->_is_even($x->{value});
1046 # return true when arg (BINT or num_str) is positive (>= 0)
1047 # we don't need $self, so undef instead of ref($_[0]) make it slightly faster
1048 my ($self,$x) = ref($_[0]) ? (undef,$_[0]) : objectify(1,@_);
1050 return 1 if $x->{sign} =~ /^\+/;
1056 # return true when arg (BINT or num_str) is negative (< 0)
1057 # we don't need $self, so undef instead of ref($_[0]) make it slightly faster
1058 my ($self,$x) = ref($_[0]) ? (undef,$_[0]) : objectify(1,@_);
1060 return 1 if ($x->{sign} =~ /^-/);
1064 ###############################################################################
1068 # multiply two numbers -- stolen from Knuth Vol 2 pg 233
1069 # (BINT or num_str, BINT or num_str) return BINT
1070 my ($self,$x,$y,@r) = objectify(2,@_);
1072 return $x if $x->modify('bmul');
1074 $r[3] = $y; # no push here
1076 return $x->bnan() if (($x->{sign} eq $nan) || ($y->{sign} eq $nan));
1078 return $x->round(@r) if $x->is_zero();
1079 return $x->bzero()->round(@r) if $y->is_zero();
1081 if (($x->{sign} =~ /^[+-]inf$/) || ($y->{sign} =~ /^[+-]inf$/))
1083 # result will always be +-inf:
1084 # +inf * +/+inf => +inf, -inf * -/-inf => +inf
1085 # +inf * -/-inf => -inf, -inf * +/+inf => -inf
1086 return $x->binf() if ($x->{sign} =~ /^\+/ && $y->{sign} =~ /^\+/);
1087 return $x->binf() if ($x->{sign} =~ /^-/ && $y->{sign} =~ /^-/);
1088 return $x->binf('-');
1091 $x->{sign} = $x->{sign} eq $y->{sign} ? '+' : '-'; # +1 * +1 or -1 * -1 => +
1093 $x->{value} = $CALC->_mul($x->{value},$y->{value}); # do actual math
1094 return $x->round(@r);
1099 # helper function that handles +-inf cases for bdiv()/bmod() to reuse code
1100 my ($self,$x,$y) = @_;
1102 # NaN if x == NaN or y == NaN or x==y==0
1103 return wantarray ? ($x->bnan(),$self->bnan()) : $x->bnan()
1104 if (($x->is_nan() || $y->is_nan()) ||
1105 ($x->is_zero() && $y->is_zero()));
1107 # +inf / +inf == -inf / -inf == 1, remainder is 0 (A / A = 1, remainder 0)
1108 if (($x->{sign} eq $y->{sign}) &&
1109 ($x->{sign} =~ /^[+-]inf$/) && ($y->{sign} =~ /^[+-]inf$/))
1111 return wantarray ? ($x->bone(),$self->bzero()) : $x->bone();
1113 # +inf / -inf == -inf / +inf == -1, remainder 0
1114 if (($x->{sign} ne $y->{sign}) &&
1115 ($x->{sign} =~ /^[+-]inf$/) && ($y->{sign} =~ /^[+-]inf$/))
1117 return wantarray ? ($x->bone('-'),$self->bzero()) : $x->bone('-');
1119 # x / +-inf => 0, remainder x (works even if x == 0)
1120 if ($y->{sign} =~ /^[+-]inf$/)
1122 my $t = $x->copy(); # binf clobbers up $x
1123 return wantarray ? ($x->bzero(),$t) : $x->bzero()
1126 # 5 / 0 => +inf, -6 / 0 => -inf
1127 # +inf / 0 = inf, inf, and -inf / 0 => -inf, -inf
1128 # exception: -8 / 0 has remainder -8, not 8
1129 # exception: -inf / 0 has remainder -inf, not inf
1132 # +-inf / 0 => special case for -inf
1133 return wantarray ? ($x,$x->copy()) : $x if $x->is_inf();
1134 if (!$x->is_zero() && !$x->is_inf())
1136 my $t = $x->copy(); # binf clobbers up $x
1138 ($x->binf($x->{sign}),$t) : $x->binf($x->{sign})
1142 # last case: +-inf / ordinary number
1144 $sign = '-inf' if substr($x->{sign},0,1) ne $y->{sign};
1146 return wantarray ? ($x,$self->bzero()) : $x;
1151 # (dividend: BINT or num_str, divisor: BINT or num_str) return
1152 # (BINT,BINT) (quo,rem) or BINT (only rem)
1153 my ($self,$x,$y,@r) = objectify(2,@_);
1155 return $x if $x->modify('bdiv');
1157 return $self->_div_inf($x,$y)
1158 if (($x->{sign} !~ /^[+-]$/) || ($y->{sign} !~ /^[+-]$/) || $y->is_zero());
1160 $r[3] = $y; # no push!
1164 wantarray ? ($x->round(@r),$self->bzero(@r)):$x->round(@r) if $x->is_zero();
1166 # Is $x in the interval [0, $y) ?
1167 my $cmp = $CALC->_acmp($x->{value},$y->{value});
1168 if (($cmp < 0) and ($x->{sign} eq $y->{sign}))
1170 return $x->bzero()->round(@r) unless wantarray;
1171 my $t = $x->copy(); # make copy first, because $x->bzero() clobbers $x
1172 return ($x->bzero()->round(@r),$t);
1176 # shortcut, both are the same, so set to +/- 1
1177 $x->__one( ($x->{sign} ne $y->{sign} ? '-' : '+') );
1178 return $x unless wantarray;
1179 return ($x->round(@r),$self->bzero(@r));
1182 # calc new sign and in case $y == +/- 1, return $x
1183 my $xsign = $x->{sign}; # keep
1184 $x->{sign} = ($x->{sign} ne $y->{sign} ? '-' : '+');
1185 # check for / +-1 (cant use $y->is_one due to '-'
1186 if ($CALC->_is_one($y->{value}))
1188 return wantarray ? ($x->round(@r),$self->bzero(@r)) : $x->round(@r);
1194 my $rem = $self->bzero();
1195 ($x->{value},$rem->{value}) = $CALC->_div($x->{value},$y->{value});
1196 $x->{sign} = '+' if $CALC->_is_zero($x->{value});
1198 if (! $CALC->_is_zero($rem->{value}))
1200 $rem->{sign} = $y->{sign};
1201 $rem = $y-$rem if $xsign ne $y->{sign}; # one of them '-'
1205 $rem->{sign} = '+'; # dont leave -0
1211 $x->{value} = $CALC->_div($x->{value},$y->{value});
1212 $x->{sign} = '+' if $CALC->_is_zero($x->{value});
1219 # modulus (or remainder)
1220 # (BINT or num_str, BINT or num_str) return BINT
1221 my ($self,$x,$y,@r) = objectify(2,@_);
1223 return $x if $x->modify('bmod');
1224 $r[3] = $y; # no push!
1225 if (($x->{sign} !~ /^[+-]$/) || ($y->{sign} !~ /^[+-]$/) || $y->is_zero())
1227 my ($d,$r) = $self->_div_inf($x,$y);
1228 return $r->round(@r);
1231 if ($CALC->can('_mod'))
1233 # calc new sign and in case $y == +/- 1, return $x
1234 $x->{value} = $CALC->_mod($x->{value},$y->{value});
1235 my $xsign = $x->{sign};
1236 if (!$CALC->_is_zero($x->{value}))
1238 $x->{sign} = $y->{sign};
1239 $x = $y-$x if $xsign ne $y->{sign}; # one of them '-'
1243 $x->{sign} = '+'; # dont leave -0
1245 return $x->round(@r);
1247 $x = (&bdiv($self,$x,$y,@r))[1]; # slow way (also rounds)
1252 # (BINT or num_str, BINT or num_str) return BINT
1253 # compute power of two numbers -- stolen from Knuth Vol 2 pg 233
1254 # modifies first argument
1255 my ($self,$x,$y,@r) = objectify(2,@_);
1257 return $x if $x->modify('bpow');
1259 $r[3] = $y; # no push!
1260 return $x if $x->{sign} =~ /^[+-]inf$/; # -inf/+inf ** x
1261 return $x->bnan() if $x->{sign} eq $nan || $y->{sign} eq $nan;
1262 return $x->bone(@r) if $y->is_zero();
1263 return $x->round(@r) if $x->is_one() || $y->is_one();
1264 if ($x->{sign} eq '-' && $CALC->_is_one($x->{value}))
1266 # if $x == -1 and odd/even y => +1/-1
1267 return $y->is_odd() ? $x->round(@r) : $x->babs()->round(@r);
1268 # my Casio FX-5500L has a bug here: -1 ** 2 is -1, but -1 * -1 is 1;
1270 # 1 ** -y => 1 / (1 ** |y|)
1271 # so do test for negative $y after above's clause
1272 return $x->bnan() if $y->{sign} eq '-';
1273 return $x->round(@r) if $x->is_zero(); # 0**y => 0 (if not y <= 0)
1275 if ($CALC->can('_pow'))
1277 $x->{value} = $CALC->_pow($x->{value},$y->{value});
1278 return $x->round(@r);
1281 # based on the assumption that shifting in base 10 is fast, and that mul
1282 # works faster if numbers are small: we count trailing zeros (this step is
1283 # O(1)..O(N), but in case of O(N) we save much more time due to this),
1284 # stripping them out of the multiplication, and add $count * $y zeros
1285 # afterwards like this:
1286 # 300 ** 3 == 300*300*300 == 3*3*3 . '0' x 2 * 3 == 27 . '0' x 6
1287 # creates deep recursion?
1288 # my $zeros = $x->_trailing_zeros();
1291 # $x->brsft($zeros,10); # remove zeros
1292 # $x->bpow($y); # recursion (will not branch into here again)
1293 # $zeros = $y * $zeros; # real number of zeros to add
1294 # $x->blsft($zeros,10);
1295 # return $x->round($a,$p,$r);
1298 my $pow2 = $self->__one();
1299 my $y1 = $class->new($y);
1300 my $two = $self->new(2);
1301 while (!$y1->is_one())
1303 $pow2->bmul($x) if $y1->is_odd();
1307 $x->bmul($pow2) unless $pow2->is_one();
1308 return $x->round(@r);
1313 # (BINT or num_str, BINT or num_str) return BINT
1314 # compute x << y, base n, y >= 0
1315 my ($self,$x,$y,$n) = objectify(2,@_);
1317 return $x if $x->modify('blsft');
1318 return $x->bnan() if ($x->{sign} !~ /^[+-]$/ || $y->{sign} !~ /^[+-]$/);
1320 $n = 2 if !defined $n; return $x->bnan() if $n <= 0 || $y->{sign} eq '-';
1322 my $t; $t = $CALC->_lsft($x->{value},$y->{value},$n) if $CALC->can('_lsft');
1325 $x->{value} = $t; return $x;
1328 return $x->bmul( $self->bpow($n, $y) );
1333 # (BINT or num_str, BINT or num_str) return BINT
1334 # compute x >> y, base n, y >= 0
1335 my ($self,$x,$y,$n) = objectify(2,@_);
1337 return $x if $x->modify('brsft');
1338 return $x->bnan() if ($x->{sign} !~ /^[+-]$/ || $y->{sign} !~ /^[+-]$/);
1340 $n = 2 if !defined $n; return $x->bnan() if $n <= 0 || $y->{sign} eq '-';
1342 my $t; $t = $CALC->_rsft($x->{value},$y->{value},$n) if $CALC->can('_rsft');
1345 $x->{value} = $t; return $x;
1348 return scalar bdiv($x, $self->bpow($n, $y));
1353 #(BINT or num_str, BINT or num_str) return BINT
1355 my ($self,$x,$y,$a,$p,$r) = objectify(2,@_);
1357 return $x if $x->modify('band');
1359 return $x->bnan() if ($x->{sign} !~ /^[+-]$/ || $y->{sign} !~ /^[+-]$/);
1360 return $x->bzero() if $y->is_zero() || $x->is_zero();
1362 my $sign = 0; # sign of result
1363 $sign = 1 if ($x->{sign} eq '-') && ($y->{sign} eq '-');
1364 my $sx = 1; $sx = -1 if $x->{sign} eq '-';
1365 my $sy = 1; $sy = -1 if $y->{sign} eq '-';
1367 if ($CALC->can('_and') && $sx == 1 && $sy == 1)
1369 $x->{value} = $CALC->_and($x->{value},$y->{value});
1370 return $x->round($a,$p,$r);
1373 my $m = Math::BigInt->bone(); my ($xr,$yr);
1374 my $x10000 = new Math::BigInt (0x1000);
1375 my $y1 = copy(ref($x),$y); # make copy
1376 $y1->babs(); # and positive
1377 my $x1 = $x->copy()->babs(); $x->bzero(); # modify x in place!
1378 use integer; # need this for negative bools
1379 while (!$x1->is_zero() && !$y1->is_zero())
1381 ($x1, $xr) = bdiv($x1, $x10000);
1382 ($y1, $yr) = bdiv($y1, $x10000);
1383 # make both op's numbers!
1384 $x->badd( bmul( $class->new(
1385 abs($sx*int($xr->numify()) & $sy*int($yr->numify()))),
1389 $x->bneg() if $sign;
1390 return $x->round($a,$p,$r);
1395 #(BINT or num_str, BINT or num_str) return BINT
1397 my ($self,$x,$y,$a,$p,$r) = objectify(2,@_);
1399 return $x if $x->modify('bior');
1401 return $x->bnan() if ($x->{sign} !~ /^[+-]$/ || $y->{sign} !~ /^[+-]$/);
1402 return $x if $y->is_zero();
1404 my $sign = 0; # sign of result
1405 $sign = 1 if ($x->{sign} eq '-') || ($y->{sign} eq '-');
1406 my $sx = 1; $sx = -1 if $x->{sign} eq '-';
1407 my $sy = 1; $sy = -1 if $y->{sign} eq '-';
1409 # don't use lib for negative values
1410 if ($CALC->can('_or') && $sx == 1 && $sy == 1)
1412 $x->{value} = $CALC->_or($x->{value},$y->{value});
1413 return $x->round($a,$p,$r);
1416 my $m = Math::BigInt->bone(); my ($xr,$yr);
1417 my $x10000 = Math::BigInt->new(0x10000);
1418 my $y1 = copy(ref($x),$y); # make copy
1419 $y1->babs(); # and positive
1420 my $x1 = $x->copy()->babs(); $x->bzero(); # modify x in place!
1421 use integer; # need this for negative bools
1422 while (!$x1->is_zero() || !$y1->is_zero())
1424 ($x1, $xr) = bdiv($x1,$x10000);
1425 ($y1, $yr) = bdiv($y1,$x10000);
1426 # make both op's numbers!
1427 $x->badd( bmul( $class->new(
1428 abs($sx*int($xr->numify()) | $sy*int($yr->numify()))),
1432 $x->bneg() if $sign;
1433 return $x->round($a,$p,$r);
1438 #(BINT or num_str, BINT or num_str) return BINT
1440 my ($self,$x,$y,$a,$p,$r) = objectify(2,@_);
1442 return $x if $x->modify('bxor');
1444 return $x->bnan() if ($x->{sign} !~ /^[+-]$/ || $y->{sign} !~ /^[+-]$/);
1445 return $x if $y->is_zero();
1447 my $sign = 0; # sign of result
1448 $sign = 1 if $x->{sign} ne $y->{sign};
1449 my $sx = 1; $sx = -1 if $x->{sign} eq '-';
1450 my $sy = 1; $sy = -1 if $y->{sign} eq '-';
1452 # don't use lib for negative values
1453 if ($CALC->can('_xor') && $sx == 1 && $sy == 1)
1455 $x->{value} = $CALC->_xor($x->{value},$y->{value});
1456 return $x->round($a,$p,$r);
1459 my $m = $self->bone(); my ($xr,$yr);
1460 my $x10000 = Math::BigInt->new(0x10000);
1461 my $y1 = copy(ref($x),$y); # make copy
1462 $y1->babs(); # and positive
1463 my $x1 = $x->copy()->babs(); $x->bzero(); # modify x in place!
1464 use integer; # need this for negative bools
1465 while (!$x1->is_zero() || !$y1->is_zero())
1467 ($x1, $xr) = bdiv($x1, $x10000);
1468 ($y1, $yr) = bdiv($y1, $x10000);
1469 # make both op's numbers!
1470 $x->badd( bmul( $class->new(
1471 abs($sx*int($xr->numify()) ^ $sy*int($yr->numify()))),
1475 $x->bneg() if $sign;
1476 return $x->round($a,$p,$r);
1481 my ($self,$x) = ref($_[0]) ? (ref($_[0]),$_[0]) : objectify(1,@_);
1483 my $e = $CALC->_len($x->{value});
1484 return wantarray ? ($e,0) : $e;
1489 # return the nth decimal digit, negative values count backward, 0 is right
1493 return $CALC->_digit($x->{value},$n);
1498 # return the amount of trailing zeros in $x
1500 $x = $class->new($x) unless ref $x;
1502 return 0 if $x->is_zero() || $x->is_odd() || $x->{sign} !~ /^[+-]$/;
1504 return $CALC->_zeros($x->{value}) if $CALC->can('_zeros');
1506 # if not: since we do not know underlying internal representation:
1507 my $es = "$x"; $es =~ /([0]*)$/;
1508 return 0 if !defined $1; # no zeros
1509 return CORE::length("$1"); # as string, not as +0!
1514 my ($self,$x,$a,$p,$r) = ref($_[0]) ? (ref($_[0]),$_[0]) : objectify(1,@_);
1516 return $x->bnan() if $x->{sign} ne '+'; # -x or inf or NaN => NaN
1517 return $x->bzero($a,$p) if $x->is_zero(); # 0 => 0
1518 return $x->round($a,$p,$r) if $x->is_one(); # 1 => 1
1519 return $x->bone($a,$p) if $x < 4; # 2,3 => 1
1521 if ($CALC->can('_sqrt'))
1523 $x->{value} = $CALC->_sqrt($x->{value});
1524 return $x->round($a,$p,$r);
1528 my $l = int($x->length()/2);
1530 $x->bone(); # keep ref($x), but modify it
1533 my $last = $self->bzero();
1534 my $two = $self->new(2);
1535 my $lastlast = $x+$two;
1536 while ($last != $x && $lastlast != $x)
1538 $lastlast = $last; $last = $x;
1542 $x-- if $x * $x > $y; # overshot?
1543 return $x->round($a,$p,$r);
1548 # return a copy of the exponent (here always 0, NaN or 1 for $m == 0)
1549 my ($self,$x) = ref($_[0]) ? (ref($_[0]),$_[0]) : objectify(1,@_);
1551 if ($x->{sign} !~ /^[+-]$/)
1553 my $s = $x->{sign}; $s =~ s/^[+-]//;
1554 return $self->new($s); # -inf,+inf => inf
1556 my $e = $class->bzero();
1557 return $e->binc() if $x->is_zero();
1558 $e += $x->_trailing_zeros();
1564 # return the mantissa (compatible to Math::BigFloat, e.g. reduced)
1565 my ($self,$x) = ref($_[0]) ? (ref($_[0]),$_[0]) : objectify(1,@_);
1567 if ($x->{sign} !~ /^[+-]$/)
1569 my $s = $x->{sign}; $s =~ s/^[+]//;
1570 return $self->new($s); # +inf => inf
1573 # that's inefficient
1574 my $zeros = $m->_trailing_zeros();
1575 $m /= 10 ** $zeros if $zeros != 0;
1581 # return a copy of both the exponent and the mantissa
1582 my ($self,$x) = ref($_[0]) ? (ref($_[0]),$_[0]) : objectify(1,@_);
1584 return ($x->mantissa(),$x->exponent());
1587 ##############################################################################
1588 # rounding functions
1592 # precision: round to the $Nth digit left (+$n) or right (-$n) from the '.'
1593 # $n == 0 || $n == 1 => round to integer
1594 my $x = shift; $x = $class->new($x) unless ref $x;
1595 my ($scale,$mode) = $x->_scale_p($x->precision(),$x->round_mode(),@_);
1596 return $x if !defined $scale; # no-op
1598 # no-op for BigInts if $n <= 0
1601 $x->{_a} = undef; # clear an eventual set A
1602 $x->{_p} = $scale; return $x;
1605 $x->bround( $x->length()-$scale, $mode);
1606 $x->{_a} = undef; # bround sets {_a}
1607 $x->{_p} = $scale; # so correct it
1611 sub _scan_for_nonzero
1617 my $len = $x->length();
1618 return 0 if $len == 1; # '5' is trailed by invisible zeros
1619 my $follow = $pad - 1;
1620 return 0 if $follow > $len || $follow < 1;
1622 # since we do not know underlying represention of $x, use decimal string
1623 #my $r = substr ($$xs,-$follow);
1624 my $r = substr ("$x",-$follow);
1625 return 1 if $r =~ /[^0]/; return 0;
1630 # to make life easier for switch between MBF and MBI (autoload fxxx()
1631 # like MBF does for bxxx()?)
1633 return $x->bround(@_);
1638 # accuracy: +$n preserve $n digits from left,
1639 # -$n preserve $n digits from right (f.i. for 0.1234 style in MBF)
1641 # and overwrite the rest with 0's, return normalized number
1642 # do not return $x->bnorm(), but $x
1644 my $x = shift; $x = $class->new($x) unless ref $x;
1645 my ($scale,$mode) = $x->_scale_a($x->accuracy(),$x->round_mode(),@_);
1646 return $x if !defined $scale; # no-op
1648 if ($x->is_zero() || $scale == 0)
1650 $x->{_a} = $scale if !defined $x->{_a} || $x->{_a} > $scale; # 3 > 2
1653 return $x if $x->{sign} !~ /^[+-]$/; # inf, NaN
1655 # we have fewer digits than we want to scale to
1656 my $len = $x->length();
1657 # scale < 0, but > -len (not >=!)
1658 if (($scale < 0 && $scale < -$len-1) || ($scale >= $len))
1660 $x->{_a} = $scale if !defined $x->{_a} || $x->{_a} > $scale; # 3 > 2
1664 # count of 0's to pad, from left (+) or right (-): 9 - +6 => 3, or |-6| => 6
1665 my ($pad,$digit_round,$digit_after);
1666 $pad = $len - $scale;
1667 $pad = abs($scale-1) if $scale < 0;
1669 # do not use digit(), it is costly for binary => decimal
1671 my $xs = $CALC->_str($x->{value});
1674 # pad: 123: 0 => -1, at 1 => -2, at 2 => -3, at 3 => -4
1675 # pad+1: 123: 0 => 0, at 1 => -1, at 2 => -2, at 3 => -3
1676 $digit_round = '0'; $digit_round = substr($$xs,$pl,1) if $pad <= $len;
1677 $pl++; $pl ++ if $pad >= $len;
1678 $digit_after = '0'; $digit_after = substr($$xs,$pl,1) if $pad > 0;
1680 # print "$pad $pl $$xs dr $digit_round da $digit_after\n";
1682 # in case of 01234 we round down, for 6789 up, and only in case 5 we look
1683 # closer at the remaining digits of the original $x, remember decision
1684 my $round_up = 1; # default round up
1686 ($mode eq 'trunc') || # trunc by round down
1687 ($digit_after =~ /[01234]/) || # round down anyway,
1689 ($digit_after eq '5') && # not 5000...0000
1690 ($x->_scan_for_nonzero($pad,$xs) == 0) &&
1692 ($mode eq 'even') && ($digit_round =~ /[24680]/) ||
1693 ($mode eq 'odd') && ($digit_round =~ /[13579]/) ||
1694 ($mode eq '+inf') && ($x->{sign} eq '-') ||
1695 ($mode eq '-inf') && ($x->{sign} eq '+') ||
1696 ($mode eq 'zero') # round down if zero, sign adjusted below
1698 my $put_back = 0; # not yet modified
1700 # old code, depend on internal representation
1701 # split mantissa at $pad and then pad with zeros
1702 #my $s5 = int($pad / 5);
1706 # $x->{value}->[$i++] = 0; # replace with 5 x 0
1708 #$x->{value}->[$s5] = '00000'.$x->{value}->[$s5]; # pad with 0
1709 #my $rem = $pad % 5; # so much left over
1712 # #print "remainder $rem\n";
1713 ## #print "elem $x->{value}->[$s5]\n";
1714 # substr($x->{value}->[$s5],-$rem,$rem) = '0' x $rem; # stamp w/ '0'
1716 #$x->{value}->[$s5] = int ($x->{value}->[$s5]); # str '05' => int '5'
1717 #print ${$CALC->_str($pad->{value})}," $len\n";
1719 if (($pad > 0) && ($pad <= $len))
1721 substr($$xs,-$pad,$pad) = '0' x $pad;
1726 $x->bzero(); # round to '0'
1729 if ($round_up) # what gave test above?
1732 $pad = $len, $$xs = '0'x$pad if $scale < 0; # tlr: whack 0.51=>1.0
1734 # we modify directly the string variant instead of creating a number and
1736 my $c = 0; $pad ++; # for $pad == $len case
1737 while ($pad <= $len)
1739 $c = substr($$xs,-$pad,1) + 1; $c = '0' if $c eq '10';
1740 substr($$xs,-$pad,1) = $c; $pad++;
1741 last if $c != 0; # no overflow => early out
1743 $$xs = '1'.$$xs if $c == 0;
1745 # $x->badd( Math::BigInt->new($x->{sign}.'1'. '0' x $pad) );
1747 $x->{value} = $CALC->_new($xs) if $put_back == 1; # put back in
1749 $x->{_a} = $scale if $scale >= 0;
1752 $x->{_a} = $len+$scale;
1753 $x->{_a} = 0 if $scale < -$len;
1760 # return integer less or equal then number, since it is already integer,
1761 # always returns $self
1762 my ($self,$x,$a,$p,$r) = ref($_[0]) ? (ref($_[0]),@_) : objectify(1,@_);
1764 # not needed: return $x if $x->modify('bfloor');
1765 return $x->round($a,$p,$r);
1770 # return integer greater or equal then number, since it is already integer,
1771 # always returns $self
1772 my ($self,$x,$a,$p,$r) = ref($_[0]) ? (ref($_[0]),@_) : objectify(1,@_);
1774 # not needed: return $x if $x->modify('bceil');
1775 return $x->round($a,$p,$r);
1778 ##############################################################################
1779 # private stuff (internal use only)
1783 # internal speedup, set argument to 1, or create a +/- 1
1785 my $x = $self->bone(); # $x->{value} = $CALC->_one();
1786 $x->{sign} = shift || '+';
1792 # Overload will swap params if first one is no object ref so that the first
1793 # one is always an object ref. In this case, third param is true.
1794 # This routine is to overcome the effect of scalar,$object creating an object
1795 # of the class of this package, instead of the second param $object. This
1796 # happens inside overload, when the overload section of this package is
1797 # inherited by sub classes.
1798 # For overload cases (and this is used only there), we need to preserve the
1799 # args, hence the copy().
1800 # You can override this method in a subclass, the overload section will call
1801 # $object->_swap() to make sure it arrives at the proper subclass, with some
1802 # exceptions like '+' and '-'. To make '+' and '-' work, you also need to
1803 # specify your own overload for them.
1805 # object, (object|scalar) => preserve first and make copy
1806 # scalar, object => swapped, re-swap and create new from first
1807 # (using class of second object, not $class!!)
1808 my $self = shift; # for override in subclass
1811 my $c = ref ($_[0]) || $class; # fallback $class should not happen
1812 return ( $c->new($_[1]), $_[0] );
1814 return ( $_[0]->copy(), $_[1] );
1819 # check for strings, if yes, return objects instead
1821 # the first argument is number of args objectify() should look at it will
1822 # return $count+1 elements, the first will be a classname. This is because
1823 # overloaded '""' calls bstr($object,undef,undef) and this would result in
1824 # useless objects beeing created and thrown away. So we cannot simple loop
1825 # over @_. If the given count is 0, all arguments will be used.
1827 # If the second arg is a ref, use it as class.
1828 # If not, try to use it as classname, unless undef, then use $class
1829 # (aka Math::BigInt). The latter shouldn't happen,though.
1832 # $x->badd(1); => ref x, scalar y
1833 # Class->badd(1,2); => classname x (scalar), scalar x, scalar y
1834 # Class->badd( Class->(1),2); => classname x (scalar), ref x, scalar y
1835 # Math::BigInt::badd(1,2); => scalar x, scalar y
1836 # In the last case we check number of arguments to turn it silently into
1837 # $class,1,2. (We can not take '1' as class ;o)
1838 # badd($class,1) is not supported (it should, eventually, try to add undef)
1839 # currently it tries 'Math::BigInt' + 1, which will not work.
1841 # some shortcut for the common cases
1844 return (ref($_[1]),$_[1]) if (@_ == 2) && ($_[0]||0 == 1) && ref($_[1]);
1845 # $x->binary_op($y);
1846 #return (ref($_[1]),$_[1],$_[2]) if (@_ == 3) && ($_[0]||0 == 2)
1847 # && ref($_[1]) && ref($_[2]);
1849 my $count = abs(shift || 0);
1851 my @a; # resulting array
1854 # okay, got object as first
1859 # nope, got 1,2 (Class->xxx(1) => Class,1 and not supported)
1861 $a[0] = shift if $_[0] =~ /^[A-Z].*::/; # classname as first?
1863 # print "Now in objectify, my class is today $a[0]\n";
1872 $k = $a[0]->new($k);
1874 elsif (ref($k) ne $a[0])
1876 # foreign object, try to convert to integer
1877 $k->can('as_number') ? $k = $k->as_number() : $k = $a[0]->new($k);
1890 $k = $a[0]->new($k);
1892 elsif (ref($k) ne $a[0])
1894 # foreign object, try to convert to integer
1895 $k->can('as_number') ? $k = $k->as_number() : $k = $a[0]->new($k);
1899 push @a,@_; # return other params, too
1901 die "$class objectify needs list context" unless wantarray;
1910 my @a = @_; my $l = scalar @_; my $j = 0;
1911 for ( my $i = 0; $i < $l ; $i++,$j++ )
1913 if ($_[$i] eq ':constant')
1915 # this causes overlord er load to step in
1916 overload::constant integer => sub { $self->new(shift) };
1917 splice @a, $j, 1; $j --;
1919 elsif ($_[$i] =~ /^lib$/i)
1921 # this causes a different low lib to take care...
1922 $CALC = $_[$i+1] || '';
1923 my $s = 2; $s = 1 if @a-$j < 2; # avoid "can not modify non-existant..."
1924 splice @a, $j, $s; $j -= $s;
1927 # any non :constant stuff is handled by our parent, Exporter
1928 # even if @_ is empty, to give it a chance
1929 $self->SUPER::import(@a); # need it for subclasses
1930 $self->export_to_level(1,$self,@a); # need it for MBF
1932 # try to load core math lib
1933 my @c = split /\s*,\s*/,$CALC;
1934 push @c,'Calc'; # if all fail, try this
1935 $CALC = ''; # signal error
1936 foreach my $lib (@c)
1938 $lib = 'Math::BigInt::'.$lib if $lib !~ /^Math::BigInt/i;
1942 # Perl < 5.6.0 dies with "out of memory!" when eval() and ':constant' is
1943 # used in the same script, or eval inside import().
1944 (my $mod = $lib . '.pm') =~ s!::!/!g;
1945 # require does not automatically :: => /, so portability problems arise
1946 eval { require $mod; $lib->import( @c ); }
1950 eval "use $lib qw/@c/;";
1952 $CALC = $lib, last if $@ eq ''; # no error in loading lib?
1954 die "Couldn't load any math lib, not even the default" if $CALC eq '';
1959 # convert a (ref to) big hex string to BigInt, return undef for error
1962 my $x = Math::BigInt->bzero();
1965 $$hs =~ s/([0-9a-fA-F])_([0-9a-fA-F])/$1$2/g;
1966 $$hs =~ s/([0-9a-fA-F])_([0-9a-fA-F])/$1$2/g;
1968 return $x->bnan() if $$hs !~ /^[\-\+]?0x[0-9A-Fa-f]+$/;
1970 my $sign = '+'; $sign = '-' if ($$hs =~ /^-/);
1972 $$hs =~ s/^[+-]//; # strip sign
1973 if ($CALC->can('_from_hex'))
1975 $x->{value} = $CALC->_from_hex($hs);
1979 # fallback to pure perl
1980 my $mul = Math::BigInt->bzero(); $mul++;
1981 my $x65536 = Math::BigInt->new(65536);
1982 my $len = CORE::length($$hs)-2;
1983 $len = int($len/4); # 4-digit parts, w/o '0x'
1984 my $val; my $i = -4;
1987 $val = substr($$hs,$i,4);
1988 $val =~ s/^[+-]?0x// if $len == 0; # for last part only because
1989 $val = hex($val); # hex does not like wrong chars
1991 $x += $mul * $val if $val != 0;
1992 $mul *= $x65536 if $len >= 0; # skip last mul
1995 $x->{sign} = $sign if !$x->is_zero(); # no '-0'
2001 # convert a (ref to) big binary string to BigInt, return undef for error
2004 my $x = Math::BigInt->bzero();
2006 $$bs =~ s/([01])_([01])/$1$2/g;
2007 $$bs =~ s/([01])_([01])/$1$2/g;
2008 return $x->bnan() if $$bs !~ /^[+-]?0b[01]+$/;
2010 my $mul = Math::BigInt->bzero(); $mul++;
2011 my $x256 = Math::BigInt->new(256);
2013 my $sign = '+'; $sign = '-' if ($$bs =~ /^\-/);
2014 $$bs =~ s/^[+-]//; # strip sign
2015 if ($CALC->can('_from_bin'))
2017 $x->{value} = $CALC->_from_bin($bs);
2021 my $len = CORE::length($$bs)-2;
2022 $len = int($len/8); # 8-digit parts, w/o '0b'
2023 my $val; my $i = -8;
2026 $val = substr($$bs,$i,8);
2027 $val =~ s/^[+-]?0b// if $len == 0; # for last part only
2028 #$val = oct('0b'.$val); # does not work on Perl prior to 5.6.0
2030 # $val = ('0' x (8-CORE::length($val))).$val if CORE::length($val) < 8;
2031 $val = ord(pack('B8',substr('00000000'.$val,-8,8)));
2033 $x += $mul * $val if $val != 0;
2034 $mul *= $x256 if $len >= 0; # skip last mul
2037 $x->{sign} = $sign if !$x->is_zero();
2043 # (ref to num_str) return num_str
2044 # internal, take apart a string and return the pieces
2045 # strip leading/trailing whitespace, leading zeros, underscore and reject
2049 # strip white space at front, also extranous leading zeros
2050 $$x =~ s/^\s*([-]?)0*([0-9])/$1$2/g; # will not strip ' .2'
2051 $$x =~ s/^\s+//; # but this will
2052 $$x =~ s/\s+$//g; # strip white space at end
2054 # shortcut, if nothing to split, return early
2055 if ($$x =~ /^[+-]?\d+$/)
2057 $$x =~ s/^([+-])0*([0-9])/$2/; my $sign = $1 || '+';
2058 return (\$sign, $x, \'', \'', \0);
2061 # invalid starting char?
2062 return if $$x !~ /^[+-]?(\.?[0-9]|0b[0-1]|0x[0-9a-fA-F])/;
2064 return __from_hex($x) if $$x =~ /^[\-\+]?0x/; # hex string
2065 return __from_bin($x) if $$x =~ /^[\-\+]?0b/; # binary string
2067 # strip underscores between digits
2068 $$x =~ s/(\d)_(\d)/$1$2/g;
2069 $$x =~ s/(\d)_(\d)/$1$2/g; # do twice for 1_2_3
2071 # some possible inputs:
2072 # 2.1234 # 0.12 # 1 # 1E1 # 2.134E1 # 434E-10 # 1.02009E-2
2073 # .2 # 1_2_3.4_5_6 # 1.4E1_2_3 # 1e3 # +.2
2075 return if $$x =~ /[Ee].*[Ee]/; # more than one E => error
2077 my ($m,$e) = split /[Ee]/,$$x;
2078 $e = '0' if !defined $e || $e eq "";
2079 # sign,value for exponent,mantint,mantfrac
2080 my ($es,$ev,$mis,$miv,$mfv);
2082 if ($e =~ /^([+-]?)0*(\d+)$/) # strip leading zeros
2086 return if $m eq '.' || $m eq '';
2087 my ($mi,$mf) = split /\./,$m;
2088 $mi = '0' if !defined $mi;
2089 $mi .= '0' if $mi =~ /^[\-\+]?$/;
2090 $mf = '0' if !defined $mf || $mf eq '';
2091 if ($mi =~ /^([+-]?)0*(\d+)$/) # strip leading zeros
2093 $mis = $1||'+'; $miv = $2;
2094 return unless ($mf =~ /^(\d*?)0*$/); # strip trailing zeros
2096 return (\$mis,\$miv,\$mfv,\$es,\$ev);
2099 return; # NaN, not a number
2104 # an object might be asked to return itself as bigint on certain overloaded
2105 # operations, this does exactly this, so that sub classes can simple inherit
2106 # it or override with their own integer conversion routine
2114 # return as hex string, with prefixed 0x
2115 my $x = shift; $x = $class->new($x) if !ref($x);
2117 return $x->bstr() if $x->{sign} !~ /^[+-]$/; # inf, nan etc
2118 return '0x0' if $x->is_zero();
2120 my $es = ''; my $s = '';
2121 $s = $x->{sign} if $x->{sign} eq '-';
2122 if ($CALC->can('_as_hex'))
2124 $es = ${$CALC->_as_hex($x->{value})};
2128 my $x1 = $x->copy()->babs(); my $xr;
2129 my $x10000 = Math::BigInt->new (0x10000);
2130 while (!$x1->is_zero())
2132 ($x1, $xr) = bdiv($x1,$x10000);
2133 $es .= unpack('h4',pack('v',$xr->numify()));
2136 $es =~ s/^[0]+//; # strip leading zeros
2144 # return as binary string, with prefixed 0b
2145 my $x = shift; $x = $class->new($x) if !ref($x);
2147 return $x->bstr() if $x->{sign} !~ /^[+-]$/; # inf, nan etc
2148 return '0b0' if $x->is_zero();
2150 my $es = ''; my $s = '';
2151 $s = $x->{sign} if $x->{sign} eq '-';
2152 if ($CALC->can('_as_bin'))
2154 $es = ${$CALC->_as_bin($x->{value})};
2158 my $x1 = $x->copy()->babs(); my $xr;
2159 my $x10000 = Math::BigInt->new (0x10000);
2160 while (!$x1->is_zero())
2162 ($x1, $xr) = bdiv($x1,$x10000);
2163 $es .= unpack('b16',pack('v',$xr->numify()));
2166 $es =~ s/^[0]+//; # strip leading zeros
2172 ##############################################################################
2173 # internal calculation routines (others are in Math::BigInt::Calc etc)
2177 # (BINT or num_str, BINT or num_str) return BINT
2178 # does modify first argument
2181 my $x = shift; my $ty = shift;
2182 return $x->bnan() if ($x->{sign} eq $nan) || ($ty->{sign} eq $nan);
2183 return $x * $ty / bgcd($x,$ty);
2188 # (BINT or num_str, BINT or num_str) return BINT
2189 # does modify both arguments
2190 # GCD -- Euclids algorithm E, Knuth Vol 2 pg 296
2193 return $x->bnan() if $x->{sign} !~ /^[+-]$/ || $ty->{sign} !~ /^[+-]$/;
2195 while (!$ty->is_zero())
2197 ($x, $ty) = ($ty,bmod($x,$ty));
2202 ###############################################################################
2203 # this method return 0 if the object can be modified, or 1 for not
2204 # We use a fast use constant statement here, to avoid costly calls. Subclasses
2205 # may override it with special code (f.i. Math::BigInt::Constant does so)
2207 sub modify () { 0; }
2214 Math::BigInt - Arbitrary size integer math package
2221 $x = Math::BigInt->new($str); # defaults to 0
2222 $nan = Math::BigInt->bnan(); # create a NotANumber
2223 $zero = Math::BigInt->bzero(); # create a +0
2224 $inf = Math::BigInt->binf(); # create a +inf
2225 $inf = Math::BigInt->binf('-'); # create a -inf
2226 $one = Math::BigInt->bone(); # create a +1
2227 $one = Math::BigInt->bone('-'); # create a -1
2230 $x->is_zero(); # true if arg is +0
2231 $x->is_nan(); # true if arg is NaN
2232 $x->is_one(); # true if arg is +1
2233 $x->is_one('-'); # true if arg is -1
2234 $x->is_odd(); # true if odd, false for even
2235 $x->is_even(); # true if even, false for odd
2236 $x->is_positive(); # true if >= 0
2237 $x->is_negative(); # true if < 0
2238 $x->is_inf(sign); # true if +inf, or -inf (sign is default '+')
2240 $x->bcmp($y); # compare numbers (undef,<0,=0,>0)
2241 $x->bacmp($y); # compare absolutely (undef,<0,=0,>0)
2242 $x->sign(); # return the sign, either +,- or NaN
2243 $x->digit($n); # return the nth digit, counting from right
2244 $x->digit(-$n); # return the nth digit, counting from left
2246 # The following all modify their first argument:
2249 $x->bzero(); # set $x to 0
2250 $x->bnan(); # set $x to NaN
2251 $x->bone(); # set $x to +1
2252 $x->bone('-'); # set $x to -1
2254 $x->bneg(); # negation
2255 $x->babs(); # absolute value
2256 $x->bnorm(); # normalize (no-op)
2257 $x->bnot(); # two's complement (bit wise not)
2258 $x->binc(); # increment x by 1
2259 $x->bdec(); # decrement x by 1
2261 $x->badd($y); # addition (add $y to $x)
2262 $x->bsub($y); # subtraction (subtract $y from $x)
2263 $x->bmul($y); # multiplication (multiply $x by $y)
2264 $x->bdiv($y); # divide, set $x to quotient
2265 # return (quo,rem) or quo if scalar
2267 $x->bmod($y); # modulus (x % y)
2268 $x->bpow($y); # power of arguments (x ** y)
2269 $x->blsft($y); # left shift
2270 $x->brsft($y); # right shift
2271 $x->blsft($y,$n); # left shift, by base $n (like 10)
2272 $x->brsft($y,$n); # right shift, by base $n (like 10)
2274 $x->band($y); # bitwise and
2275 $x->bior($y); # bitwise inclusive or
2276 $x->bxor($y); # bitwise exclusive or
2277 $x->bnot(); # bitwise not (two's complement)
2279 $x->bsqrt(); # calculate square-root
2281 $x->round($A,$P,$round_mode); # round to accuracy or precision using mode $r
2282 $x->bround($N); # accuracy: preserve $N digits
2283 $x->bfround($N); # round to $Nth digit, no-op for BigInts
2285 # The following do not modify their arguments in BigInt, but do in BigFloat:
2286 $x->bfloor(); # return integer less or equal than $x
2287 $x->bceil(); # return integer greater or equal than $x
2289 # The following do not modify their arguments:
2291 bgcd(@values); # greatest common divisor (no OO style)
2292 blcm(@values); # lowest common multiplicator (no OO style)
2294 $x->length(); # return number of digits in number
2295 ($x,$f) = $x->length(); # length of number and length of fraction part,
2296 # latter is always 0 digits long for BigInt's
2298 $x->exponent(); # return exponent as BigInt
2299 $x->mantissa(); # return (signed) mantissa as BigInt
2300 $x->parts(); # return (mantissa,exponent) as BigInt
2301 $x->copy(); # make a true copy of $x (unlike $y = $x;)
2302 $x->as_number(); # return as BigInt (in BigInt: same as copy())
2304 # conversation to string
2305 $x->bstr(); # normalized string
2306 $x->bsstr(); # normalized string in scientific notation
2307 $x->as_hex(); # as signed hexadecimal string with prefixed 0x
2308 $x->as_bin(); # as signed binary string with prefixed 0b
2312 All operators (inlcuding basic math operations) are overloaded if you
2313 declare your big integers as
2315 $i = new Math::BigInt '123_456_789_123_456_789';
2317 Operations with overloaded operators preserve the arguments which is
2318 exactly what you expect.
2322 =item Canonical notation
2324 Big integer values are strings of the form C</^[+-]\d+$/> with leading
2327 '-0' canonical value '-0', normalized '0'
2328 ' -123_123_123' canonical value '-123123123'
2329 '1_23_456_7890' canonical value '1234567890'
2333 Input values to these routines may be either Math::BigInt objects or
2334 strings of the form C</^\s*[+-]?[\d]+\.?[\d]*E?[+-]?[\d]*$/>.
2336 You can include one underscore between any two digits.
2338 This means integer values like 1.01E2 or even 1000E-2 are also accepted.
2339 Non integer values result in NaN.
2341 Math::BigInt::new() defaults to 0, while Math::BigInt::new('') results
2344 bnorm() on a BigInt object is now effectively a no-op, since the numbers
2345 are always stored in normalized form. On a string, it creates a BigInt
2350 Output values are BigInt objects (normalized), except for bstr(), which
2351 returns a string in normalized form.
2352 Some routines (C<is_odd()>, C<is_even()>, C<is_zero()>, C<is_one()>,
2353 C<is_nan()>) return true or false, while others (C<bcmp()>, C<bacmp()>)
2354 return either undef, <0, 0 or >0 and are suited for sort.
2358 =head1 ACCURACY and PRECISION
2360 Since version v1.33, Math::BigInt and Math::BigFloat have full support for
2361 accuracy and precision based rounding, both automatically after every
2362 operation as well as manually.
2364 This section describes the accuracy/precision handling in Math::Big* as it
2365 used to be and as it is now, complete with an explanation of all terms and
2368 Not yet implemented things (but with correct description) are marked with '!',
2369 things that need to be answered are marked with '?'.
2371 In the next paragraph follows a short description of terms used here (because
2372 these may differ from terms used by others people or documentation).
2374 During the rest of this document, the shortcuts A (for accuracy), P (for
2375 precision), F (fallback) and R (rounding mode) will be used.
2379 A fixed number of digits before (positive) or after (negative)
2380 the decimal point. For example, 123.45 has a precision of -2. 0 means an
2381 integer like 123 (or 120). A precision of 2 means two digits to the left
2382 of the decimal point are zero, so 123 with P = 1 becomes 120. Note that
2383 numbers with zeros before the decimal point may have different precisions,
2384 because 1200 can have p = 0, 1 or 2 (depending on what the inital value
2385 was). It could also have p < 0, when the digits after the decimal point
2388 The string output (of floating point numbers) will be padded with zeros:
2390 Initial value P A Result String
2391 ------------------------------------------------------------
2392 1234.01 -3 1000 1000
2395 1234.001 1 1234 1234.0
2397 1234.01 2 1234.01 1234.01
2398 1234.01 5 1234.01 1234.01000
2400 For BigInts, no padding occurs.
2404 Number of significant digits. Leading zeros are not counted. A
2405 number may have an accuracy greater than the non-zero digits
2406 when there are zeros in it or trailing zeros. For example, 123.456 has
2407 A of 6, 10203 has 5, 123.0506 has 7, 123.450000 has 8 and 0.000123 has 3.
2409 The string output (of floating point numbers) will be padded with zeros:
2411 Initial value P A Result String
2412 ------------------------------------------------------------
2414 1234.01 6 1234.01 1234.01
2415 1234.1 8 1234.1 1234.1000
2417 For BigInts, no padding occurs.
2421 When both A and P are undefined, this is used as a fallback accuracy when
2424 =head2 Rounding mode R
2426 When rounding a number, different 'styles' or 'kinds'
2427 of rounding are possible. (Note that random rounding, as in
2428 Math::Round, is not implemented.)
2434 truncation invariably removes all digits following the
2435 rounding place, replacing them with zeros. Thus, 987.65 rounded
2436 to tens (P=1) becomes 980, and rounded to the fourth sigdig
2437 becomes 987.6 (A=4). 123.456 rounded to the second place after the
2438 decimal point (P=-2) becomes 123.46.
2440 All other implemented styles of rounding attempt to round to the
2441 "nearest digit." If the digit D immediately to the right of the
2442 rounding place (skipping the decimal point) is greater than 5, the
2443 number is incremented at the rounding place (possibly causing a
2444 cascade of incrementation): e.g. when rounding to units, 0.9 rounds
2445 to 1, and -19.9 rounds to -20. If D < 5, the number is similarly
2446 truncated at the rounding place: e.g. when rounding to units, 0.4
2447 rounds to 0, and -19.4 rounds to -19.
2449 However the results of other styles of rounding differ if the
2450 digit immediately to the right of the rounding place (skipping the
2451 decimal point) is 5 and if there are no digits, or no digits other
2452 than 0, after that 5. In such cases:
2456 rounds the digit at the rounding place to 0, 2, 4, 6, or 8
2457 if it is not already. E.g., when rounding to the first sigdig, 0.45
2458 becomes 0.4, -0.55 becomes -0.6, but 0.4501 becomes 0.5.
2462 rounds the digit at the rounding place to 1, 3, 5, 7, or 9 if
2463 it is not already. E.g., when rounding to the first sigdig, 0.45
2464 becomes 0.5, -0.55 becomes -0.5, but 0.5501 becomes 0.6.
2468 round to plus infinity, i.e. always round up. E.g., when
2469 rounding to the first sigdig, 0.45 becomes 0.5, -0.55 becomes -0.5,
2470 and 0.4501 also becomes 0.5.
2474 round to minus infinity, i.e. always round down. E.g., when
2475 rounding to the first sigdig, 0.45 becomes 0.4, -0.55 becomes -0.6,
2476 but 0.4501 becomes 0.5.
2480 round to zero, i.e. positive numbers down, negative ones up.
2481 E.g., when rounding to the first sigdig, 0.45 becomes 0.4, -0.55
2482 becomes -0.5, but 0.4501 becomes 0.5.
2486 The handling of A & P in MBI/MBF (the old core code shipped with Perl
2487 versions <= 5.7.2) is like this:
2493 * ffround($p) is able to round to $p number of digits after the decimal
2495 * otherwise P is unused
2497 =item Accuracy (significant digits)
2499 * fround($a) rounds to $a significant digits
2500 * only fdiv() and fsqrt() take A as (optional) paramater
2501 + other operations simply create the same number (fneg etc), or more (fmul)
2503 + rounding/truncating is only done when explicitly calling one of fround
2504 or ffround, and never for BigInt (not implemented)
2505 * fsqrt() simply hands its accuracy argument over to fdiv.
2506 * the documentation and the comment in the code indicate two different ways
2507 on how fdiv() determines the maximum number of digits it should calculate,
2508 and the actual code does yet another thing
2510 max($Math::BigFloat::div_scale,length(dividend)+length(divisor))
2512 result has at most max(scale, length(dividend), length(divisor)) digits
2514 scale = max(scale, length(dividend)-1,length(divisor)-1);
2515 scale += length(divisior) - length(dividend);
2516 So for lx = 3, ly = 9, scale = 10, scale will actually be 16 (10+9-3).
2517 Actually, the 'difference' added to the scale is calculated from the
2518 number of "significant digits" in dividend and divisor, which is derived
2519 by looking at the length of the mantissa. Which is wrong, since it includes
2520 the + sign (oups) and actually gets 2 for '+100' and 4 for '+101'. Oups
2521 again. Thus 124/3 with div_scale=1 will get you '41.3' based on the strange
2522 assumption that 124 has 3 significant digits, while 120/7 will get you
2523 '17', not '17.1' since 120 is thought to have 2 significant digits.
2524 The rounding after the division then uses the remainder and $y to determine
2525 wether it must round up or down.
2526 ? I have no idea which is the right way. That's why I used a slightly more
2527 ? simple scheme and tweaked the few failing testcases to match it.
2531 This is how it works now:
2535 =item Setting/Accessing
2537 * You can set the A global via $Math::BigInt::accuracy or
2538 $Math::BigFloat::accuracy or whatever class you are using.
2539 * You can also set P globally by using $Math::SomeClass::precision likewise.
2540 * Globals are classwide, and not inherited by subclasses.
2541 * to undefine A, use $Math::SomeCLass::accuracy = undef
2542 * to undefine P, use $Math::SomeClass::precision = undef
2543 * To be valid, A must be > 0, P can have any value.
2544 * If P is negative, this means round to the P'th place to the right of the
2545 decimal point; positive values mean to the left of the decimal point.
2546 P of 0 means round to integer.
2547 * to find out the current global A, take $Math::SomeClass::accuracy
2548 * use $x->accuracy() for the local setting of $x.
2549 * to find out the current global P, take $Math::SomeClass::precision
2550 * use $x->precision() for the local setting
2552 =item Creating numbers
2554 !* When you create a number, there should be a way to define its A & P
2555 * When a number without specific A or P is created, but the globals are
2556 defined, these should be used to round the number immediately and also
2557 stored locally with the number. Thus changing the global defaults later on
2558 will not change the A or P of previously created numbers (i.e., A and P of
2559 $x will be what was in effect when $x was created)
2563 * If A or P are enabled/defined, they are used to round the result of each
2564 operation according to the rules below
2565 * Negative P is ignored in Math::BigInt, since BigInts never have digits
2566 after the decimal point
2567 * Math::BigFloat uses Math::BigInts internally, but setting A or P inside
2568 Math::BigInt as globals should not tamper with the parts of a BigFloat.
2569 Thus a flag is used to mark all Math::BigFloat numbers as 'never round'
2573 * It only makes sense that a number has only one of A or P at a time.
2574 Since you can set/get both A and P, there is a rule that will practically
2575 enforce only A or P to be in effect at a time, even if both are set.
2576 This is called precedence.
2577 !* If two objects are involved in an operation, and one of them has A in
2578 ! effect, and the other P, this should result in a warning or an error,
2580 * A takes precendence over P (Hint: A comes before P). If A is defined, it
2581 is used, otherwise P is used. If neither of them is defined, nothing is
2582 used, i.e. the result will have as many digits as it can (with an
2583 exception for fdiv/fsqrt) and will not be rounded.
2584 * There is another setting for fdiv() (and thus for fsqrt()). If neither of
2585 A or P is defined, fdiv() will use a fallback (F) of $div_scale digits.
2586 If either the dividend's or the divisor's mantissa has more digits than
2587 the value of F, the higher value will be used instead of F.
2588 This is to limit the digits (A) of the result (just consider what would
2589 happen with unlimited A and P in the case of 1/3 :-)
2590 * fdiv will calculate 1 more digit than required (determined by
2591 A, P or F), and, if F is not used, round the result
2592 (this will still fail in the case of a result like 0.12345000000001 with A
2593 or P of 5, but this can not be helped - or can it?)
2594 * Thus you can have the math done by on Math::Big* class in three modes:
2595 + never round (this is the default):
2596 This is done by setting A and P to undef. No math operation
2597 will round the result, with fdiv() and fsqrt() as exceptions to guard
2598 against overflows. You must explicitely call bround(), bfround() or
2599 round() (the latter with parameters).
2600 Note: Once you have rounded a number, the settings will 'stick' on it
2601 and 'infect' all other numbers engaged in math operations with it, since
2602 local settings have the highest precedence. So, to get SaferRound[tm],
2603 use a copy() before rounding like this:
2605 $x = Math::BigFloat->new(12.34);
2606 $y = Math::BigFloat->new(98.76);
2607 $z = $x * $y; # 1218.6984
2608 print $x->copy()->fround(3); # 12.3 (but A is now 3!)
2609 $z = $x * $y; # still 1218.6984, without
2610 # copy would have been 1210!
2612 + round after each op:
2613 After each single operation (except for testing like is_zero()), the
2614 method round() is called and the result is rounded appropriately. By
2615 setting proper values for A and P, you can have all-the-same-A or
2616 all-the-same-P modes. For example, Math::Currency might set A to undef,
2617 and P to -2, globally.
2619 ?Maybe an extra option that forbids local A & P settings would be in order,
2620 ?so that intermediate rounding does not 'poison' further math?
2622 =item Overriding globals
2624 * you will be able to give A, P and R as an argument to all the calculation
2625 routines; the second parameter is A, the third one is P, and the fourth is
2626 R (shift place by one for binary operations like add). P is used only if
2627 the first parameter (A) is undefined. These three parameters override the
2628 globals in the order detailed as follows, i.e. the first defined value
2630 (local: per object, global: global default, parameter: argument to sub)
2633 + local A (if defined on both of the operands: smaller one is taken)
2634 + local P (if defined on both of the operands: smaller one is taken)
2638 * fsqrt() will hand its arguments to fdiv(), as it used to, only now for two
2639 arguments (A and P) instead of one
2641 =item Local settings
2643 * You can set A and P locally by using $x->accuracy() and $x->precision()
2644 and thus force different A and P for different objects/numbers.
2645 * Setting A or P this way immediately rounds $x to the new value.
2649 * the rounding routines will use the respective global or local settings.
2650 fround()/bround() is for accuracy rounding, while ffround()/bfround()
2652 * the two rounding functions take as the second parameter one of the
2653 following rounding modes (R):
2654 'even', 'odd', '+inf', '-inf', 'zero', 'trunc'
2655 * you can set and get the global R by using Math::SomeClass->round_mode()
2656 or by setting $Math::SomeClass::round_mode
2657 * after each operation, $result->round() is called, and the result may
2658 eventually be rounded (that is, if A or P were set either locally,
2659 globally or as parameter to the operation)
2660 * to manually round a number, call $x->round($A,$P,$round_mode);
2661 this will round the number by using the appropriate rounding function
2662 and then normalize it.
2663 * rounding modifies the local settings of the number:
2665 $x = Math::BigFloat->new(123.456);
2669 Here 4 takes precedence over 5, so 123.5 is the result and $x->accuracy()
2670 will be 4 from now on.
2672 =item Default values
2681 * The defaults are set up so that the new code gives the same results as
2682 the old code (except in a few cases on fdiv):
2683 + Both A and P are undefined and thus will not be used for rounding
2684 after each operation.
2685 + round() is thus a no-op, unless given extra parameters A and P
2691 The actual numbers are stored as unsigned big integers (with seperate sign).
2692 You should neither care about nor depend on the internal representation; it
2693 might change without notice. Use only method calls like C<< $x->sign(); >>
2694 instead relying on the internal hash keys like in C<< $x->{sign}; >>.
2698 Math with the numbers is done (by default) by a module called
2699 Math::BigInt::Calc. This is equivalent to saying:
2701 use Math::BigInt lib => 'Calc';
2703 You can change this by using:
2705 use Math::BigInt lib => 'BitVect';
2707 The following would first try to find Math::BigInt::Foo, then
2708 Math::BigInt::Bar, and when this also fails, revert to Math::BigInt::Calc:
2710 use Math::BigInt lib => 'Foo,Math::BigInt::Bar';
2712 Calc.pm uses as internal format an array of elements of some decimal base
2713 (usually 1e5, but this might change to 1e7) with the least significant digit
2714 first, while BitVect.pm uses a bit vector of base 2, most significant bit
2715 first. Other modules might use even different means of representing the
2716 numbers. See the respective module documentation for further details.
2720 The sign is either '+', '-', 'NaN', '+inf' or '-inf' and stored seperately.
2722 A sign of 'NaN' is used to represent the result when input arguments are not
2723 numbers or as a result of 0/0. '+inf' and '-inf' represent plus respectively
2724 minus infinity. You will get '+inf' when dividing a positive number by 0, and
2725 '-inf' when dividing any negative number by 0.
2727 =head2 mantissa(), exponent() and parts()
2729 C<mantissa()> and C<exponent()> return the said parts of the BigInt such
2732 $m = $x->mantissa();
2733 $e = $x->exponent();
2734 $y = $m * ( 10 ** $e );
2735 print "ok\n" if $x == $y;
2737 C<< ($m,$e) = $x->parts() >> is just a shortcut that gives you both of them
2738 in one go. Both the returned mantissa and exponent have a sign.
2740 Currently, for BigInts C<$e> will be always 0, except for NaN, +inf and -inf,
2741 where it will be NaN; and for $x == 0, where it will be 1
2742 (to be compatible with Math::BigFloat's internal representation of a zero as
2745 C<$m> will always be a copy of the original number. The relation between $e
2746 and $m might change in the future, but will always be equivalent in a
2747 numerical sense, e.g. $m might get minimized.
2753 sub bint { Math::BigInt->new(shift); }
2755 $x = Math::BigInt->bstr("1234") # string "1234"
2756 $x = "$x"; # same as bstr()
2757 $x = Math::BigInt->bneg("1234"); # Bigint "-1234"
2758 $x = Math::BigInt->babs("-12345"); # Bigint "12345"
2759 $x = Math::BigInt->bnorm("-0 00"); # BigInt "0"
2760 $x = bint(1) + bint(2); # BigInt "3"
2761 $x = bint(1) + "2"; # ditto (auto-BigIntify of "2")
2762 $x = bint(1); # BigInt "1"
2763 $x = $x + 5 / 2; # BigInt "3"
2764 $x = $x ** 3; # BigInt "27"
2765 $x *= 2; # BigInt "54"
2766 $x = Math::BigInt->new(0); # BigInt "0"
2768 $x = Math::BigInt->badd(4,5) # BigInt "9"
2769 print $x->bsstr(); # 9e+0
2771 Examples for rounding:
2776 $x = Math::BigFloat->new(123.4567);
2777 $y = Math::BigFloat->new(123.456789);
2778 Math::BigFloat->accuracy(4); # no more A than 4
2780 ok ($x->copy()->fround(),123.4); # even rounding
2781 print $x->copy()->fround(),"\n"; # 123.4
2782 Math::BigFloat->round_mode('odd'); # round to odd
2783 print $x->copy()->fround(),"\n"; # 123.5
2784 Math::BigFloat->accuracy(5); # no more A than 5
2785 Math::BigFloat->round_mode('odd'); # round to odd
2786 print $x->copy()->fround(),"\n"; # 123.46
2787 $y = $x->copy()->fround(4),"\n"; # A = 4: 123.4
2788 print "$y, ",$y->accuracy(),"\n"; # 123.4, 4
2790 Math::BigFloat->accuracy(undef); # A not important now
2791 Math::BigFloat->precision(2); # P important
2792 print $x->copy()->bnorm(),"\n"; # 123.46
2793 print $x->copy()->fround(),"\n"; # 123.46
2795 Examples for converting:
2797 my $x = Math::BigInt->new('0b1'.'01' x 123);
2798 print "bin: ",$x->as_bin()," hex:",$x->as_hex()," dec: ",$x,"\n";
2800 =head1 Autocreating constants
2802 After C<use Math::BigInt ':constant'> all the B<integer> decimal constants
2803 in the given scope are converted to C<Math::BigInt>. This conversion
2804 happens at compile time.
2808 perl -MMath::BigInt=:constant -e 'print 2**100,"\n"'
2810 prints the integer value of C<2**100>. Note that without conversion of
2811 constants the expression 2**100 will be calculated as perl scalar.
2813 Please note that strings and floating point constants are not affected,
2816 use Math::BigInt qw/:constant/;
2818 $x = 1234567890123456789012345678901234567890
2819 + 123456789123456789;
2820 $y = '1234567890123456789012345678901234567890'
2821 + '123456789123456789';
2823 do not work. You need an explicit Math::BigInt->new() around one of the
2824 operands. You should also quote large constants to protect loss of precision:
2828 $x = Math::BigInt->new('1234567889123456789123456789123456789');
2830 Without the quotes Perl would convert the large number to a floating point
2831 constant at compile time and then hand the result to BigInt, which results in
2832 an truncated result or a NaN.
2836 Using the form $x += $y; etc over $x = $x + $y is faster, since a copy of $x
2837 must be made in the second case. For long numbers, the copy can eat up to 20%
2838 of the work (in the case of addition/subtraction, less for
2839 multiplication/division). If $y is very small compared to $x, the form
2840 $x += $y is MUCH faster than $x = $x + $y since making the copy of $x takes
2841 more time then the actual addition.
2843 With a technique called copy-on-write, the cost of copying with overload could
2844 be minimized or even completely avoided. A test implementation of COW did show
2845 performance gains for overloaded math, but introduced a performance loss due
2846 to a constant overhead for all other operatons.
2848 The rewritten version of this module is slower on certain operations, like
2849 new(), bstr() and numify(). The reason are that it does now more work and
2850 handles more cases. The time spent in these operations is usually gained in
2851 the other operations so that programs on the average should get faster. If
2852 they don't, please contect the author.
2854 Some operations may be slower for small numbers, but are significantly faster
2855 for big numbers. Other operations are now constant (O(1), like bneg(), babs()
2856 etc), instead of O(N) and thus nearly always take much less time. These
2857 optimizations were done on purpose.
2859 If you find the Calc module to slow, try to install any of the replacement
2860 modules and see if they help you.
2862 =head2 Alternative math libraries
2864 You can use an alternative library to drive Math::BigInt via:
2866 use Math::BigInt lib => 'Module';
2868 See L<MATH LIBRARY> for more information.
2870 For more benchmark results see L<http://bloodgate.com/perl/benchmarks.html>.
2876 =item Out of Memory!
2878 Under Perl prior to 5.6.0 having an C<use Math::BigInt ':constant';> and
2879 C<eval()> in your code will crash with "Out of memory". This is probably an
2880 overload/exporter bug. You can workaround by not having C<eval()>
2881 and ':constant' at the same time or upgrade your Perl to a newer version.
2883 =item Fails to load Calc on Perl prior 5.6.0
2885 Since eval(' use ...') can not be used in conjunction with ':constant', BigInt
2886 will fall back to eval { require ... } when loading the math lib on Perls
2887 prior to 5.6.0. This simple replaces '::' with '/' and thus might fail on
2888 filesystems using a different seperator.
2894 Some things might not work as you expect them. Below is documented what is
2895 known to be troublesome:
2899 =item stringify, bstr(), bsstr() and 'cmp'
2901 Both stringify and bstr() now drop the leading '+'. The old code would return
2902 '+3', the new returns '3'. This is to be consistent with Perl and to make
2903 cmp (especially with overloading) to work as you expect. It also solves
2904 problems with Test.pm, it's ok() uses 'eq' internally.
2906 Mark said, when asked about to drop the '+' altogether, or make only cmp work:
2908 I agree (with the first alternative), don't add the '+' on positive
2909 numbers. It's not as important anymore with the new internal
2910 form for numbers. It made doing things like abs and neg easier,
2911 but those have to be done differently now anyway.
2913 So, the following examples will now work all as expected:
2916 BEGIN { plan tests => 1 }
2919 my $x = new Math::BigInt 3*3;
2920 my $y = new Math::BigInt 3*3;
2923 print "$x eq 9" if $x eq $y;
2924 print "$x eq 9" if $x eq '9';
2925 print "$x eq 9" if $x eq 3*3;
2927 Additionally, the following still works:
2929 print "$x == 9" if $x == $y;
2930 print "$x == 9" if $x == 9;
2931 print "$x == 9" if $x == 3*3;
2933 There is now a C<bsstr()> method to get the string in scientific notation aka
2934 C<1e+2> instead of C<100>. Be advised that overloaded 'eq' always uses bstr()
2935 for comparisation, but Perl will represent some numbers as 100 and others
2936 as 1e+308. If in doubt, convert both arguments to Math::BigInt before doing eq:
2939 BEGIN { plan tests => 3 }
2942 $x = Math::BigInt->new('1e56'); $y = 1e56;
2943 ok ($x,$y); # will fail
2944 ok ($x->bsstr(),$y); # okay
2945 $y = Math::BigInt->new($y);
2948 Alternatively, simple use <=> for comparisations, that will get it always
2949 right. There is not yet a way to get a number automatically represented as
2950 a string that matches exactly the way Perl represents it.
2954 C<int()> will return (at least for Perl v5.7.1 and up) another BigInt, not a
2957 $x = Math::BigInt->new(123);
2958 $y = int($x); # BigInt 123
2959 $x = Math::BigFloat->new(123.45);
2960 $y = int($x); # BigInt 123
2962 In all Perl versions you can use C<as_number()> for the same effect:
2964 $x = Math::BigFloat->new(123.45);
2965 $y = $x->as_number(); # BigInt 123
2967 This also works for other subclasses, like Math::String.
2969 It is yet unlcear whether overloaded int() should return a scalar or a BigInt.
2973 The following will probably not do what you expect:
2975 $c = Math::BigInt->new(123);
2976 print $c->length(),"\n"; # prints 30
2978 It prints both the number of digits in the number and in the fraction part
2979 since print calls C<length()> in list context. Use something like:
2981 print scalar $c->length(),"\n"; # prints 3
2985 The following will probably not do what you expect:
2987 print $c->bdiv(10000),"\n";
2989 It prints both quotient and remainder since print calls C<bdiv()> in list
2990 context. Also, C<bdiv()> will modify $c, so be carefull. You probably want
2993 print $c / 10000,"\n";
2994 print scalar $c->bdiv(10000),"\n"; # or if you want to modify $c
2998 The quotient is always the greatest integer less than or equal to the
2999 real-valued quotient of the two operands, and the remainder (when it is
3000 nonzero) always has the same sign as the second operand; so, for
3010 As a consequence, the behavior of the operator % agrees with the
3011 behavior of Perl's built-in % operator (as documented in the perlop
3012 manpage), and the equation
3014 $x == ($x / $y) * $y + ($x % $y)
3016 holds true for any $x and $y, which justifies calling the two return
3017 values of bdiv() the quotient and remainder. The only exception to this rule
3018 are when $y == 0 and $x is negative, then the remainder will also be
3019 negative. See below under "infinity handling" for the reasoning behing this.
3021 Perl's 'use integer;' changes the behaviour of % and / for scalars, but will
3022 not change BigInt's way to do things. This is because under 'use integer' Perl
3023 will do what the underlying C thinks is right and this is different for each
3024 system. If you need BigInt's behaving exactly like Perl's 'use integer', bug
3025 the author to implement it ;)
3027 =item infinity handling
3029 Here are some examples that explain the reasons why certain results occur while
3032 The following table shows the result of the division and the remainder, so that
3033 the equation above holds true. Some "ordinary" cases are strewn in to show more
3034 clearly the reasoning:
3036 A / B = C, R so that C * B + R = A
3037 =========================================================
3038 5 / 8 = 0, 5 0 * 8 + 5 = 5
3039 0 / 8 = 0, 0 0 * 8 + 0 = 0
3040 0 / inf = 0, 0 0 * inf + 0 = 0
3041 0 /-inf = 0, 0 0 * -inf + 0 = 0
3042 5 / inf = 0, 5 0 * inf + 5 = 5
3043 5 /-inf = 0, 5 0 * -inf + 5 = 5
3044 -5/ inf = 0, -5 0 * inf + -5 = -5
3045 -5/-inf = 0, -5 0 * -inf + -5 = -5
3046 inf/ 5 = inf, 0 inf * 5 + 0 = inf
3047 -inf/ 5 = -inf, 0 -inf * 5 + 0 = -inf
3048 inf/ -5 = -inf, 0 -inf * -5 + 0 = inf
3049 -inf/ -5 = inf, 0 inf * -5 + 0 = -inf
3050 5/ 5 = 1, 0 1 * 5 + 0 = 5
3051 -5/ -5 = 1, 0 1 * -5 + 0 = -5
3052 inf/ inf = 1, 0 1 * inf + 0 = inf
3053 -inf/-inf = 1, 0 1 * -inf + 0 = -inf
3054 inf/-inf = -1, 0 -1 * -inf + 0 = inf
3055 -inf/ inf = -1, 0 1 * -inf + 0 = -inf
3056 8/ 0 = inf, 8 inf * 0 + 8 = 8
3057 inf/ 0 = inf, inf inf * 0 + inf = inf
3060 These cases below violate the "remainder has the sign of the second of the two
3061 arguments", since they wouldn't match up otherwise.
3063 A / B = C, R so that C * B + R = A
3064 ========================================================
3065 -inf/ 0 = -inf, -inf -inf * 0 + inf = -inf
3066 -8/ 0 = -inf, -8 -inf * 0 + 8 = -8
3068 =item Modifying and =
3072 $x = Math::BigFloat->new(5);
3075 It will not do what you think, e.g. making a copy of $x. Instead it just makes
3076 a second reference to the B<same> object and stores it in $y. Thus anything
3077 that modifies $x (except overloaded operators) will modify $y, and vice versa.
3078 Or in other words, C<=> is only safe if you modify your BigInts only via
3079 overloaded math. As soon as you use a method call it breaks:
3082 print "$x, $y\n"; # prints '10, 10'
3084 If you want a true copy of $x, use:
3088 You can also chain the calls like this, this will make first a copy and then
3091 $y = $x->copy()->bmul(2);
3093 See also the documentation for overload.pm regarding C<=>.
3097 C<bpow()> (and the rounding functions) now modifies the first argument and
3098 returns it, unlike the old code which left it alone and only returned the
3099 result. This is to be consistent with C<badd()> etc. The first three will
3100 modify $x, the last one won't:
3102 print bpow($x,$i),"\n"; # modify $x
3103 print $x->bpow($i),"\n"; # ditto
3104 print $x **= $i,"\n"; # the same
3105 print $x ** $i,"\n"; # leave $x alone
3107 The form C<$x **= $y> is faster than C<$x = $x ** $y;>, though.
3109 =item Overloading -$x
3119 since overload calls C<sub($x,0,1);> instead of C<neg($x)>. The first variant
3120 needs to preserve $x since it does not know that it later will get overwritten.
3121 This makes a copy of $x and takes O(N), but $x->bneg() is O(1).
3123 With Copy-On-Write, this issue would be gone, but C-o-W is not implemented
3124 since it is slower for all other things.
3126 =item Mixing different object types
3128 In Perl you will get a floating point value if you do one of the following:
3134 With overloaded math, only the first two variants will result in a BigFloat:
3139 $mbf = Math::BigFloat->new(5);
3140 $mbi2 = Math::BigInteger->new(5);
3141 $mbi = Math::BigInteger->new(2);
3143 # what actually gets called:
3144 $float = $mbf + $mbi; # $mbf->badd()
3145 $float = $mbf / $mbi; # $mbf->bdiv()
3146 $integer = $mbi + $mbf; # $mbi->badd()
3147 $integer = $mbi2 / $mbi; # $mbi2->bdiv()
3148 $integer = $mbi2 / $mbf; # $mbi2->bdiv()
3150 This is because math with overloaded operators follows the first (dominating)
3151 operand, and the operation of that is called and returns thus the result. So,
3152 Math::BigInt::bdiv() will always return a Math::BigInt, regardless whether
3153 the result should be a Math::BigFloat or the second operant is one.
3155 To get a Math::BigFloat you either need to call the operation manually,
3156 make sure the operands are already of the proper type or casted to that type
3157 via Math::BigFloat->new():
3159 $float = Math::BigFloat->new($mbi2) / $mbi; # = 2.5
3161 Beware of simple "casting" the entire expression, this would only convert
3162 the already computed result:
3164 $float = Math::BigFloat->new($mbi2 / $mbi); # = 2.0 thus wrong!
3166 Beware also of the order of more complicated expressions like:
3168 $integer = ($mbi2 + $mbi) / $mbf; # int / float => int
3169 $integer = $mbi2 / Math::BigFloat->new($mbi); # ditto
3171 If in doubt, break the expression into simpler terms, or cast all operands
3172 to the desired resulting type.
3174 Scalar values are a bit different, since:
3179 will both result in the proper type due to the way the overloaded math works.
3181 This section also applies to other overloaded math packages, like Math::String.
3185 C<bsqrt()> works only good if the result is a big integer, e.g. the square
3186 root of 144 is 12, but from 12 the square root is 3, regardless of rounding
3189 If you want a better approximation of the square root, then use:
3191 $x = Math::BigFloat->new(12);
3192 Math::BigFloat->precision(0);
3193 Math::BigFloat->round_mode('even');
3194 print $x->copy->bsqrt(),"\n"; # 4
3196 Math::BigFloat->precision(2);
3197 print $x->bsqrt(),"\n"; # 3.46
3198 print $x->bsqrt(3),"\n"; # 3.464
3204 This program is free software; you may redistribute it and/or modify it under
3205 the same terms as Perl itself.
3209 L<Math::BigFloat> and L<Math::Big> as well as L<Math::BigInt::BitVect>,
3210 L<Math::BigInt::Pari> and L<Math::BigInt::GMP>.
3213 L<http://search.cpan.org/search?mode=module&query=Math%3A%3ABigInt> contains
3214 more documentation including a full version history, testcases, empty
3215 subclass files and benchmarks.
3219 Original code by Mark Biggar, overloaded interface by Ilya Zakharevich.
3220 Completely rewritten by Tels http://bloodgate.com in late 2000, 2001.