4 # "Mike had an infinite amount to do and a negative amount of time in which
5 # to do it." - Before and After
8 # The following hash values are used:
9 # value: unsigned int with actual value (as a Math::BigInt::Calc or similiar)
10 # sign : +,-,NaN,+inf,-inf
13 # _f : flags, used by MBF to flag parts of a float as untouchable
15 # Remember not to take shortcuts ala $xs = $x->{value}; $CALC->foo($xs); since
16 # underlying lib might change the reference!
18 my $class = "Math::BigInt";
21 # This is a patched v1.60, containing a fix for the "1234567890\n" bug
24 @ISA = qw( Exporter );
25 @EXPORT_OK = qw( objectify _swap bgcd blcm);
26 use vars qw/$round_mode $accuracy $precision $div_scale $rnd_mode/;
27 use vars qw/$upgrade $downgrade/;
30 # Inside overload, the first arg is always an object. If the original code had
31 # it reversed (like $x = 2 * $y), then the third paramater indicates this
32 # swapping. To make it work, we use a helper routine which not only reswaps the
33 # params, but also makes a new object in this case. See _swap() for details,
34 # especially the cases of operators with different classes.
36 # For overloaded ops with only one argument we simple use $_[0]->copy() to
37 # preserve the argument.
39 # Thus inheritance of overload operators becomes possible and transparent for
40 # our subclasses without the need to repeat the entire overload section there.
43 '=' => sub { $_[0]->copy(); },
45 # '+' and '-' do not use _swap, since it is a triffle slower. If you want to
46 # override _swap (if ever), then override overload of '+' and '-', too!
47 # for sub it is a bit tricky to keep b: b-a => -a+b
48 '-' => sub { my $c = $_[0]->copy; $_[2] ?
49 $c->bneg()->badd($_[1]) :
51 '+' => sub { $_[0]->copy()->badd($_[1]); },
53 # some shortcuts for speed (assumes that reversed order of arguments is routed
54 # to normal '+' and we thus can always modify first arg. If this is changed,
55 # this breaks and must be adjusted.)
56 '+=' => sub { $_[0]->badd($_[1]); },
57 '-=' => sub { $_[0]->bsub($_[1]); },
58 '*=' => sub { $_[0]->bmul($_[1]); },
59 '/=' => sub { scalar $_[0]->bdiv($_[1]); },
60 '%=' => sub { $_[0]->bmod($_[1]); },
61 '^=' => sub { $_[0]->bxor($_[1]); },
62 '&=' => sub { $_[0]->band($_[1]); },
63 '|=' => sub { $_[0]->bior($_[1]); },
64 '**=' => sub { $_[0]->bpow($_[1]); },
66 # not supported by Perl yet
67 '..' => \&_pointpoint,
69 '<=>' => sub { $_[2] ?
70 ref($_[0])->bcmp($_[1],$_[0]) :
74 "$_[1]" cmp $_[0]->bstr() :
75 $_[0]->bstr() cmp "$_[1]" },
77 'log' => sub { $_[0]->copy()->blog(); },
78 'int' => sub { $_[0]->copy(); },
79 'neg' => sub { $_[0]->copy()->bneg(); },
80 'abs' => sub { $_[0]->copy()->babs(); },
81 'sqrt' => sub { $_[0]->copy()->bsqrt(); },
82 '~' => sub { $_[0]->copy()->bnot(); },
84 '*' => sub { my @a = ref($_[0])->_swap(@_); $a[0]->bmul($a[1]); },
85 '/' => sub { my @a = ref($_[0])->_swap(@_);scalar $a[0]->bdiv($a[1]);},
86 '%' => sub { my @a = ref($_[0])->_swap(@_); $a[0]->bmod($a[1]); },
87 '**' => sub { my @a = ref($_[0])->_swap(@_); $a[0]->bpow($a[1]); },
88 '<<' => sub { my @a = ref($_[0])->_swap(@_); $a[0]->blsft($a[1]); },
89 '>>' => sub { my @a = ref($_[0])->_swap(@_); $a[0]->brsft($a[1]); },
91 '&' => sub { my @a = ref($_[0])->_swap(@_); $a[0]->band($a[1]); },
92 '|' => sub { my @a = ref($_[0])->_swap(@_); $a[0]->bior($a[1]); },
93 '^' => sub { my @a = ref($_[0])->_swap(@_); $a[0]->bxor($a[1]); },
95 # can modify arg of ++ and --, so avoid a new-copy for speed, but don't
96 # use $_[0]->__one(), it modifies $_[0] to be 1!
97 '++' => sub { $_[0]->binc() },
98 '--' => sub { $_[0]->bdec() },
100 # if overloaded, O(1) instead of O(N) and twice as fast for small numbers
102 # this kludge is needed for perl prior 5.6.0 since returning 0 here fails :-/
103 # v5.6.1 dumps on that: return !$_[0]->is_zero() || undef; :-(
104 my $t = !$_[0]->is_zero();
109 # the original qw() does not work with the TIESCALAR below, why?
110 # Order of arguments unsignificant
111 '""' => sub { $_[0]->bstr(); },
112 '0+' => sub { $_[0]->numify(); }
115 ##############################################################################
116 # global constants, flags and accessory
118 use constant MB_NEVER_ROUND => 0x0001;
120 my $NaNOK=1; # are NaNs ok?
121 my $nan = 'NaN'; # constants for easier life
123 my $CALC = 'Math::BigInt::Calc'; # module to do low level math
124 my $IMPORT = 0; # did import() yet?
126 $round_mode = 'even'; # one of 'even', 'odd', '+inf', '-inf', 'zero' or 'trunc'
131 $upgrade = undef; # default is no upgrade
132 $downgrade = undef; # default is no downgrade
134 ##############################################################################
135 # the old code had $rnd_mode, so we need to support it, too
138 sub TIESCALAR { my ($class) = @_; bless \$round_mode, $class; }
139 sub FETCH { return $round_mode; }
140 sub STORE { $rnd_mode = $_[0]->round_mode($_[1]); }
142 BEGIN { tie $rnd_mode, 'Math::BigInt'; }
144 ##############################################################################
149 # make Class->round_mode() work
151 my $class = ref($self) || $self || __PACKAGE__;
155 die "Unknown round mode $m"
156 if $m !~ /^(even|odd|\+inf|\-inf|zero|trunc)$/;
157 return ${"${class}::round_mode"} = $m;
159 return ${"${class}::round_mode"};
165 # make Class->upgrade() work
167 my $class = ref($self) || $self || __PACKAGE__;
168 # need to set new value?
172 return ${"${class}::upgrade"} = $u;
174 return ${"${class}::upgrade"};
180 # make Class->downgrade() work
182 my $class = ref($self) || $self || __PACKAGE__;
183 # need to set new value?
187 return ${"${class}::downgrade"} = $u;
189 return ${"${class}::downgrade"};
195 # make Class->round_mode() work
197 my $class = ref($self) || $self || __PACKAGE__;
200 die ('div_scale must be greater than zero') if $_[0] < 0;
201 ${"${class}::div_scale"} = shift;
203 return ${"${class}::div_scale"};
208 # $x->accuracy($a); ref($x) $a
209 # $x->accuracy(); ref($x)
210 # Class->accuracy(); class
211 # Class->accuracy($a); class $a
214 my $class = ref($x) || $x || __PACKAGE__;
217 # need to set new value?
221 die ('accuracy must not be zero') if defined $a && $a == 0;
224 # $object->accuracy() or fallback to global
225 $x->bround($a) if defined $a;
226 $x->{_a} = $a; # set/overwrite, even if not rounded
227 $x->{_p} = undef; # clear P
232 ${"${class}::accuracy"} = $a;
233 ${"${class}::precision"} = undef; # clear P
235 return $a; # shortcut
239 # $object->accuracy() or fallback to global
240 $r = $x->{_a} if ref($x);
241 # but don't return global undef, when $x's accuracy is 0!
242 $r = ${"${class}::accuracy"} if !defined $r;
248 # $x->precision($p); ref($x) $p
249 # $x->precision(); ref($x)
250 # Class->precision(); class
251 # Class->precision($p); class $p
254 my $class = ref($x) || $x || __PACKAGE__;
257 # need to set new value?
263 # $object->precision() or fallback to global
264 $x->bfround($p) if defined $p;
265 $x->{_p} = $p; # set/overwrite, even if not rounded
266 $x->{_a} = undef; # clear A
271 ${"${class}::precision"} = $p;
272 ${"${class}::accuracy"} = undef; # clear A
274 return $p; # shortcut
278 # $object->precision() or fallback to global
279 $r = $x->{_p} if ref($x);
280 # but don't return global undef, when $x's precision is 0!
281 $r = ${"${class}::precision"} if !defined $r;
287 # return (later set?) configuration data as hash ref
288 my $class = shift || 'Math::BigInt';
294 lib_version => ${"${lib}::VERSION"},
298 qw/upgrade downgrade precision accuracy round_mode VERSION div_scale/)
300 $cfg->{lc($_)} = ${"${class}::$_"};
307 # select accuracy parameter based on precedence,
308 # used by bround() and bfround(), may return undef for scale (means no op)
309 my ($x,$s,$m,$scale,$mode) = @_;
310 $scale = $x->{_a} if !defined $scale;
311 $scale = $s if (!defined $scale);
312 $mode = $m if !defined $mode;
313 return ($scale,$mode);
318 # select precision parameter based on precedence,
319 # used by bround() and bfround(), may return undef for scale (means no op)
320 my ($x,$s,$m,$scale,$mode) = @_;
321 $scale = $x->{_p} if !defined $scale;
322 $scale = $s if (!defined $scale);
323 $mode = $m if !defined $mode;
324 return ($scale,$mode);
327 ##############################################################################
335 # if two arguments, the first one is the class to "swallow" subclasses
343 return unless ref($x); # only for objects
345 my $self = {}; bless $self,$c;
347 foreach my $k (keys %$x)
351 $self->{value} = $CALC->_copy($x->{value}); next;
353 if (!($r = ref($x->{$k})))
355 $self->{$k} = $x->{$k}; next;
359 $self->{$k} = \${$x->{$k}};
361 elsif ($r eq 'ARRAY')
363 $self->{$k} = [ @{$x->{$k}} ];
367 # only one level deep!
368 foreach my $h (keys %{$x->{$k}})
370 $self->{$k}->{$h} = $x->{$k}->{$h};
376 if ($xk->can('copy'))
378 $self->{$k} = $xk->copy();
382 $self->{$k} = $xk->new($xk);
391 # create a new BigInt object from a string or another BigInt object.
392 # see hash keys documented at top
394 # the argument could be an object, so avoid ||, && etc on it, this would
395 # cause costly overloaded code to be called. The only allowed ops are
398 my ($class,$wanted,$a,$p,$r) = @_;
400 # avoid numify-calls by not using || on $wanted!
401 return $class->bzero($a,$p) if !defined $wanted; # default to 0
402 return $class->copy($wanted,$a,$p,$r)
403 if ref($wanted) && $wanted->isa($class); # MBI or subclass
405 $class->import() if $IMPORT == 0; # make require work
407 my $self = bless {}, $class;
409 # shortcut for "normal" numbers
410 if ((!ref $wanted) && ($wanted =~ /^([+-]?)[1-9][0-9]*\z/))
412 $self->{sign} = $1 || '+';
414 if ($wanted =~ /^[+-]/)
416 # remove sign without touching wanted
417 my $t = $wanted; $t =~ s/^[+-]//; $ref = \$t;
419 $self->{value} = $CALC->_new($ref);
421 if ( (defined $a) || (defined $p)
422 || (defined ${"${class}::precision"})
423 || (defined ${"${class}::accuracy"})
426 $self->round($a,$p,$r) unless (@_ == 4 && !defined $a && !defined $p);
431 # handle '+inf', '-inf' first
432 if ($wanted =~ /^[+-]?inf$/)
434 $self->{value} = $CALC->_zero();
435 $self->{sign} = $wanted; $self->{sign} = '+inf' if $self->{sign} eq 'inf';
438 # split str in m mantissa, e exponent, i integer, f fraction, v value, s sign
439 my ($mis,$miv,$mfv,$es,$ev) = _split(\$wanted);
442 die "$wanted is not a number initialized to $class" if !$NaNOK;
444 $self->{value} = $CALC->_zero();
445 $self->{sign} = $nan;
450 # _from_hex or _from_bin
451 $self->{value} = $mis->{value};
452 $self->{sign} = $mis->{sign};
453 return $self; # throw away $mis
455 # make integer from mantissa by adjusting exp, then convert to bigint
456 $self->{sign} = $$mis; # store sign
457 $self->{value} = $CALC->_zero(); # for all the NaN cases
458 my $e = int("$$es$$ev"); # exponent (avoid recursion)
461 my $diff = $e - CORE::length($$mfv);
462 if ($diff < 0) # Not integer
465 return $upgrade->new($wanted,$a,$p,$r) if defined $upgrade;
466 $self->{sign} = $nan;
470 # adjust fraction and add it to value
471 # print "diff > 0 $$miv\n";
472 $$miv = $$miv . ($$mfv . '0' x $diff);
477 if ($$mfv ne '') # e <= 0
479 # fraction and negative/zero E => NOI
480 #print "NOI 2 \$\$mfv '$$mfv'\n";
481 return $upgrade->new($wanted,$a,$p,$r) if defined $upgrade;
482 $self->{sign} = $nan;
486 # xE-y, and empty mfv
489 if ($$miv !~ s/0{$e}$//) # can strip so many zero's?
492 return $upgrade->new($wanted,$a,$p,$r) if defined $upgrade;
493 $self->{sign} = $nan;
497 $self->{sign} = '+' if $$miv eq '0'; # normalize -0 => +0
498 $self->{value} = $CALC->_new($miv) if $self->{sign} =~ /^[+-]$/;
499 # if any of the globals is set, use them to round and store them inside $self
500 # do not round for new($x,undef,undef) since that is used by MBF to signal
502 $self->round($a,$p,$r) unless @_ == 4 && !defined $a && !defined $p;
508 # create a bigint 'NaN', if given a BigInt, set it to 'NaN'
510 $self = $class if !defined $self;
513 my $c = $self; $self = {}; bless $self, $c;
515 $self->import() if $IMPORT == 0; # make require work
516 return if $self->modify('bnan');
518 if ($self->can('_bnan'))
520 # use subclass to initialize
525 # otherwise do our own thing
526 $self->{value} = $CALC->_zero();
528 $self->{sign} = $nan;
529 delete $self->{_a}; delete $self->{_p}; # rounding NaN is silly
535 # create a bigint '+-inf', if given a BigInt, set it to '+-inf'
536 # the sign is either '+', or if given, used from there
538 my $sign = shift; $sign = '+' if !defined $sign || $sign !~ /^-(inf)?$/;
539 $self = $class if !defined $self;
542 my $c = $self; $self = {}; bless $self, $c;
544 $self->import() if $IMPORT == 0; # make require work
545 return if $self->modify('binf');
547 if ($self->can('_binf'))
549 # use subclass to initialize
554 # otherwise do our own thing
555 $self->{value} = $CALC->_zero();
557 $sign = $sign . 'inf' if $sign !~ /inf$/; # - => -inf
558 $self->{sign} = $sign;
559 ($self->{_a},$self->{_p}) = @_; # take over requested rounding
565 # create a bigint '+0', if given a BigInt, set it to 0
567 $self = $class if !defined $self;
571 my $c = $self; $self = {}; bless $self, $c;
573 $self->import() if $IMPORT == 0; # make require work
574 return if $self->modify('bzero');
576 if ($self->can('_bzero'))
578 # use subclass to initialize
583 # otherwise do our own thing
584 $self->{value} = $CALC->_zero();
591 # call like: $x->bzero($a,$p,$r,$y);
592 ($self,$self->{_a},$self->{_p}) = $self->_find_round_parameters(@_);
597 if ( (!defined $self->{_a}) || (defined $_[0] && $_[0] > $self->{_a}));
599 if ( (!defined $self->{_p}) || (defined $_[1] && $_[1] > $self->{_p}));
607 # create a bigint '+1' (or -1 if given sign '-'),
608 # if given a BigInt, set it to +1 or -1, respecively
610 my $sign = shift; $sign = '+' if !defined $sign || $sign ne '-';
611 $self = $class if !defined $self;
615 my $c = $self; $self = {}; bless $self, $c;
617 $self->import() if $IMPORT == 0; # make require work
618 return if $self->modify('bone');
620 if ($self->can('_bone'))
622 # use subclass to initialize
627 # otherwise do our own thing
628 $self->{value} = $CALC->_one();
630 $self->{sign} = $sign;
635 # call like: $x->bone($sign,$a,$p,$r,$y);
636 ($self,$self->{_a},$self->{_p}) = $self->_find_round_parameters(@_);
641 if ( (!defined $self->{_a}) || (defined $_[0] && $_[0] > $self->{_a}));
643 if ( (!defined $self->{_p}) || (defined $_[1] && $_[1] > $self->{_p}));
649 ##############################################################################
650 # string conversation
654 # (ref to BFLOAT or num_str ) return num_str
655 # Convert number from internal format to scientific string format.
656 # internal format is always normalized (no leading zeros, "-0E0" => "+0E0")
657 my $x = shift; $class = ref($x) || $x; $x = $class->new(shift) if !ref($x);
658 # my ($self,$x) = ref($_[0]) ? (ref($_[0]),$_[0]) : objectify(1,@_);
660 if ($x->{sign} !~ /^[+-]$/)
662 return $x->{sign} unless $x->{sign} eq '+inf'; # -inf, NaN
665 my ($m,$e) = $x->parts();
666 # e can only be positive
668 # MBF: my $s = $e->{sign}; $s = '' if $s eq '-'; my $sep = 'e'.$s;
669 return $m->bstr().$sign.$e->bstr();
674 # make a string from bigint object
675 my $x = shift; $class = ref($x) || $x; $x = $class->new(shift) if !ref($x);
676 # my ($self,$x) = ref($_[0]) ? (ref($_[0]),$_[0]) : objectify(1,@_);
678 if ($x->{sign} !~ /^[+-]$/)
680 return $x->{sign} unless $x->{sign} eq '+inf'; # -inf, NaN
683 my $es = ''; $es = $x->{sign} if $x->{sign} eq '-';
684 return $es.${$CALC->_str($x->{value})};
689 # Make a "normal" scalar from a BigInt object
690 my $x = shift; $x = $class->new($x) unless ref $x;
691 return $x->{sign} if $x->{sign} !~ /^[+-]$/;
692 my $num = $CALC->_num($x->{value});
693 return -$num if $x->{sign} eq '-';
697 ##############################################################################
698 # public stuff (usually prefixed with "b")
702 # return the sign of the number: +/-/-inf/+inf/NaN
703 my ($self,$x) = ref($_[0]) ? (ref($_[0]),$_[0]) : objectify(1,@_);
708 sub _find_round_parameters
710 # After any operation or when calling round(), the result is rounded by
711 # regarding the A & P from arguments, local parameters, or globals.
713 # This procedure finds the round parameters, but it is for speed reasons
714 # duplicated in round. Otherwise, it is tested by the testsuite and used
717 my ($self,$a,$p,$r,@args) = @_;
718 # $a accuracy, if given by caller
719 # $p precision, if given by caller
720 # $r round_mode, if given by caller
721 # @args all 'other' arguments (0 for unary, 1 for binary ops)
723 # leave bigfloat parts alone
724 return ($self) if exists $self->{_f} && $self->{_f} & MB_NEVER_ROUND != 0;
726 my $c = ref($self); # find out class of argument(s)
729 # now pick $a or $p, but only if we have got "arguments"
732 foreach ($self,@args)
734 # take the defined one, or if both defined, the one that is smaller
735 $a = $_->{_a} if (defined $_->{_a}) && (!defined $a || $_->{_a} < $a);
740 # even if $a is defined, take $p, to signal error for both defined
741 foreach ($self,@args)
743 # take the defined one, or if both defined, the one that is bigger
745 $p = $_->{_p} if (defined $_->{_p}) && (!defined $p || $_->{_p} > $p);
748 # if still none defined, use globals (#2)
749 $a = ${"$c\::accuracy"} unless defined $a;
750 $p = ${"$c\::precision"} unless defined $p;
753 return ($self) unless defined $a || defined $p; # early out
755 # set A and set P is an fatal error
756 return ($self->bnan()) if defined $a && defined $p;
758 $r = ${"$c\::round_mode"} unless defined $r;
759 die "Unknown round mode '$r'" if $r !~ /^(even|odd|\+inf|\-inf|zero|trunc)$/;
761 return ($self,$a,$p,$r);
766 # Round $self according to given parameters, or given second argument's
767 # parameters or global defaults
769 # for speed reasons, _find_round_parameters is embeded here:
771 my ($self,$a,$p,$r,@args) = @_;
772 # $a accuracy, if given by caller
773 # $p precision, if given by caller
774 # $r round_mode, if given by caller
775 # @args all 'other' arguments (0 for unary, 1 for binary ops)
777 # leave bigfloat parts alone
778 return ($self) if exists $self->{_f} && $self->{_f} & MB_NEVER_ROUND != 0;
780 my $c = ref($self); # find out class of argument(s)
783 # now pick $a or $p, but only if we have got "arguments"
786 foreach ($self,@args)
788 # take the defined one, or if both defined, the one that is smaller
789 $a = $_->{_a} if (defined $_->{_a}) && (!defined $a || $_->{_a} < $a);
794 # even if $a is defined, take $p, to signal error for both defined
795 foreach ($self,@args)
797 # take the defined one, or if both defined, the one that is bigger
799 $p = $_->{_p} if (defined $_->{_p}) && (!defined $p || $_->{_p} > $p);
802 # if still none defined, use globals (#2)
803 $a = ${"$c\::accuracy"} unless defined $a;
804 $p = ${"$c\::precision"} unless defined $p;
807 return $self unless defined $a || defined $p; # early out
809 # set A and set P is an fatal error
810 return $self->bnan() if defined $a && defined $p;
812 $r = ${"$c\::round_mode"} unless defined $r;
813 die "Unknown round mode '$r'" if $r !~ /^(even|odd|\+inf|\-inf|zero|trunc)$/;
815 # now round, by calling either fround or ffround:
818 $self->bround($a,$r) if !defined $self->{_a} || $self->{_a} >= $a;
820 else # both can't be undefined due to early out
822 $self->bfround($p,$r) if !defined $self->{_p} || $self->{_p} <= $p;
824 $self->bnorm(); # after round, normalize
829 # (numstr or BINT) return BINT
830 # Normalize number -- no-op here
831 my ($self,$x) = ref($_[0]) ? (ref($_[0]),$_[0]) : objectify(1,@_);
837 # (BINT or num_str) return BINT
838 # make number absolute, or return absolute BINT from string
839 my ($self,$x) = ref($_[0]) ? (ref($_[0]),$_[0]) : objectify(1,@_);
841 return $x if $x->modify('babs');
842 # post-normalized abs for internal use (does nothing for NaN)
843 $x->{sign} =~ s/^-/+/;
849 # (BINT or num_str) return BINT
850 # negate number or make a negated number from string
851 my ($self,$x) = ref($_[0]) ? (ref($_[0]),$_[0]) : objectify(1,@_);
853 return $x if $x->modify('bneg');
855 # for +0 dont negate (to have always normalized)
856 $x->{sign} =~ tr/+-/-+/ if !$x->is_zero(); # does nothing for NaN
862 # Compares 2 values. Returns one of undef, <0, =0, >0. (suitable for sort)
863 # (BINT or num_str, BINT or num_str) return cond_code
866 my ($self,$x,$y) = (ref($_[0]),@_);
868 # objectify is costly, so avoid it
869 if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1])))
871 ($self,$x,$y) = objectify(2,@_);
874 if (($x->{sign} !~ /^[+-]$/) || ($y->{sign} !~ /^[+-]$/))
876 # handle +-inf and NaN
877 return undef if (($x->{sign} eq $nan) || ($y->{sign} eq $nan));
878 return 0 if $x->{sign} eq $y->{sign} && $x->{sign} =~ /^[+-]inf$/;
879 return +1 if $x->{sign} eq '+inf';
880 return -1 if $x->{sign} eq '-inf';
881 return -1 if $y->{sign} eq '+inf';
884 # check sign for speed first
885 return 1 if $x->{sign} eq '+' && $y->{sign} eq '-'; # does also 0 <=> -y
886 return -1 if $x->{sign} eq '-' && $y->{sign} eq '+'; # does also -x <=> 0
888 # have same sign, so compare absolute values. Don't make tests for zero here
889 # because it's actually slower than testin in Calc (especially w/ Pari et al)
891 # post-normalized compare for internal use (honors signs)
892 if ($x->{sign} eq '+')
895 return $CALC->_acmp($x->{value},$y->{value});
899 $CALC->_acmp($y->{value},$x->{value}); # swaped (lib returns 0,1,-1)
904 # Compares 2 values, ignoring their signs.
905 # Returns one of undef, <0, =0, >0. (suitable for sort)
906 # (BINT, BINT) return cond_code
909 my ($self,$x,$y) = (ref($_[0]),@_);
910 # objectify is costly, so avoid it
911 if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1])))
913 ($self,$x,$y) = objectify(2,@_);
916 if (($x->{sign} !~ /^[+-]$/) || ($y->{sign} !~ /^[+-]$/))
918 # handle +-inf and NaN
919 return undef if (($x->{sign} eq $nan) || ($y->{sign} eq $nan));
920 return 0 if $x->{sign} =~ /^[+-]inf$/ && $y->{sign} =~ /^[+-]inf$/;
921 return +1; # inf is always bigger
923 $CALC->_acmp($x->{value},$y->{value}); # lib does only 0,1,-1
928 # add second arg (BINT or string) to first (BINT) (modifies first)
929 # return result as BINT
932 my ($self,$x,$y,@r) = (ref($_[0]),@_);
933 # objectify is costly, so avoid it
934 if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1])))
936 ($self,$x,$y,@r) = objectify(2,@_);
939 return $x if $x->modify('badd');
940 return $upgrade->badd($x,$y,@r) if defined $upgrade &&
941 ((!$x->isa($self)) || (!$y->isa($self)));
943 $r[3] = $y; # no push!
944 # inf and NaN handling
945 if (($x->{sign} !~ /^[+-]$/) || ($y->{sign} !~ /^[+-]$/))
948 return $x->bnan() if (($x->{sign} eq $nan) || ($y->{sign} eq $nan));
950 if (($x->{sign} =~ /^[+-]inf$/) && ($y->{sign} =~ /^[+-]inf$/))
952 # +inf++inf or -inf+-inf => same, rest is NaN
953 return $x if $x->{sign} eq $y->{sign};
956 # +-inf + something => +inf
957 # something +-inf => +-inf
958 $x->{sign} = $y->{sign}, return $x if $y->{sign} =~ /^[+-]inf$/;
962 my ($sx, $sy) = ( $x->{sign}, $y->{sign} ); # get signs
966 $x->{value} = $CALC->_add($x->{value},$y->{value}); # same sign, abs add
971 my $a = $CALC->_acmp ($y->{value},$x->{value}); # absolute compare
974 #print "swapped sub (a=$a)\n";
975 $x->{value} = $CALC->_sub($y->{value},$x->{value},1); # abs sub w/ swap
980 # speedup, if equal, set result to 0
981 #print "equal sub, result = 0\n";
982 $x->{value} = $CALC->_zero();
987 #print "unswapped sub (a=$a)\n";
988 $x->{value} = $CALC->_sub($x->{value}, $y->{value}); # abs sub
992 $x->round(@r) if !exists $x->{_f} || $x->{_f} & MB_NEVER_ROUND == 0;
998 # (BINT or num_str, BINT or num_str) return num_str
999 # subtract second arg from first, modify first
1002 my ($self,$x,$y,@r) = (ref($_[0]),@_);
1003 # objectify is costly, so avoid it
1004 if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1])))
1006 ($self,$x,$y,@r) = objectify(2,@_);
1009 return $x if $x->modify('bsub');
1011 # upgrade done by badd():
1012 # return $upgrade->badd($x,$y,@r) if defined $upgrade &&
1013 # ((!$x->isa($self)) || (!$y->isa($self)));
1017 $x->round(@r) if !exists $x->{_f} || $x->{_f} & MB_NEVER_ROUND == 0;
1021 $y->{sign} =~ tr/+\-/-+/; # does nothing for NaN
1022 $x->badd($y,@r); # badd does not leave internal zeros
1023 $y->{sign} =~ tr/+\-/-+/; # refix $y (does nothing for NaN)
1024 $x; # already rounded by badd() or no round necc.
1029 # increment arg by one
1030 my ($self,$x,$a,$p,$r) = ref($_[0]) ? (ref($_[0]),@_) : objectify(1,@_);
1031 return $x if $x->modify('binc');
1033 if ($x->{sign} eq '+')
1035 $x->{value} = $CALC->_inc($x->{value});
1036 $x->round($a,$p,$r) if !exists $x->{_f} || $x->{_f} & MB_NEVER_ROUND == 0;
1039 elsif ($x->{sign} eq '-')
1041 $x->{value} = $CALC->_dec($x->{value});
1042 $x->{sign} = '+' if $CALC->_is_zero($x->{value}); # -1 +1 => -0 => +0
1043 $x->round($a,$p,$r) if !exists $x->{_f} || $x->{_f} & MB_NEVER_ROUND == 0;
1046 # inf, nan handling etc
1047 $x->badd($self->__one(),$a,$p,$r); # badd does round
1052 # decrement arg by one
1053 my ($self,$x,$a,$p,$r) = ref($_[0]) ? (ref($_[0]),@_) : objectify(1,@_);
1054 return $x if $x->modify('bdec');
1056 my $zero = $CALC->_is_zero($x->{value}) && $x->{sign} eq '+';
1058 if (($x->{sign} eq '-') || $zero)
1060 $x->{value} = $CALC->_inc($x->{value});
1061 $x->{sign} = '-' if $zero; # 0 => 1 => -1
1062 $x->{sign} = '+' if $CALC->_is_zero($x->{value}); # -1 +1 => -0 => +0
1063 $x->round($a,$p,$r) if !exists $x->{_f} || $x->{_f} & MB_NEVER_ROUND == 0;
1067 elsif ($x->{sign} eq '+')
1069 $x->{value} = $CALC->_dec($x->{value});
1070 $x->round($a,$p,$r) if !exists $x->{_f} || $x->{_f} & MB_NEVER_ROUND == 0;
1073 # inf, nan handling etc
1074 $x->badd($self->__one('-'),$a,$p,$r); # badd does round
1079 # not implemented yet
1080 my ($self,$x,$base,$a,$p,$r) = ref($_[0]) ? (ref($_[0]),@_) : objectify(1,@_);
1082 return $upgrade->blog($x,$base,$a,$p,$r) if defined $upgrade;
1089 # (BINT or num_str, BINT or num_str) return BINT
1090 # does not modify arguments, but returns new object
1091 # Lowest Common Multiplicator
1093 my $y = shift; my ($x);
1100 $x = $class->new($y);
1102 while (@_) { $x = __lcm($x,shift); }
1108 # (BINT or num_str, BINT or num_str) return BINT
1109 # does not modify arguments, but returns new object
1110 # GCD -- Euclids algorithm, variant C (Knuth Vol 3, pg 341 ff)
1113 $y = __PACKAGE__->new($y) if !ref($y);
1115 my $x = $y->copy(); # keep arguments
1116 if ($CALC->can('_gcd'))
1120 $y = shift; $y = $self->new($y) if !ref($y);
1121 next if $y->is_zero();
1122 return $x->bnan() if $y->{sign} !~ /^[+-]$/; # y NaN?
1123 $x->{value} = $CALC->_gcd($x->{value},$y->{value}); last if $x->is_one();
1130 $y = shift; $y = $self->new($y) if !ref($y);
1131 $x = __gcd($x,$y->copy()); last if $x->is_one(); # _gcd handles NaN
1139 # (num_str or BINT) return BINT
1140 # represent ~x as twos-complement number
1141 # we don't need $self, so undef instead of ref($_[0]) make it slightly faster
1142 my ($self,$x,$a,$p,$r) = ref($_[0]) ? (undef,@_) : objectify(1,@_);
1144 return $x if $x->modify('bnot');
1145 $x->bneg()->bdec(); # bdec already does round
1148 # is_foo test routines
1152 # return true if arg (BINT or num_str) is zero (array '+', '0')
1153 # we don't need $self, so undef instead of ref($_[0]) make it slightly faster
1154 my ($self,$x) = ref($_[0]) ? (undef,$_[0]) : objectify(1,@_);
1156 return 0 if $x->{sign} !~ /^\+$/; # -, NaN & +-inf aren't
1157 $CALC->_is_zero($x->{value});
1162 # return true if arg (BINT or num_str) is NaN
1163 my ($self,$x) = ref($_[0]) ? (ref($_[0]),$_[0]) : objectify(1,@_);
1165 return 1 if $x->{sign} eq $nan;
1171 # return true if arg (BINT or num_str) is +-inf
1172 my ($self,$x,$sign) = ref($_[0]) ? (ref($_[0]),@_) : objectify(1,@_);
1174 $sign = '' if !defined $sign;
1175 return 1 if $sign eq $x->{sign}; # match ("+inf" eq "+inf")
1176 return 0 if $sign !~ /^([+-]|)$/;
1180 return 1 if ($x->{sign} =~ /^[+-]inf$/);
1183 $sign = quotemeta($sign.'inf');
1184 return 1 if ($x->{sign} =~ /^$sign$/);
1190 # return true if arg (BINT or num_str) is +1
1191 # or -1 if sign is given
1192 # we don't need $self, so undef instead of ref($_[0]) make it slightly faster
1193 my ($self,$x,$sign) = ref($_[0]) ? (undef,@_) : objectify(1,@_);
1195 $sign = '' if !defined $sign; $sign = '+' if $sign ne '-';
1197 return 0 if $x->{sign} ne $sign; # -1 != +1, NaN, +-inf aren't either
1198 $CALC->_is_one($x->{value});
1203 # return true when arg (BINT or num_str) is odd, false for even
1204 # we don't need $self, so undef instead of ref($_[0]) make it slightly faster
1205 my ($self,$x) = ref($_[0]) ? (undef,$_[0]) : objectify(1,@_);
1207 return 0 if $x->{sign} !~ /^[+-]$/; # NaN & +-inf aren't
1208 $CALC->_is_odd($x->{value});
1213 # return true when arg (BINT or num_str) is even, false for odd
1214 # we don't need $self, so undef instead of ref($_[0]) make it slightly faster
1215 my ($self,$x) = ref($_[0]) ? (undef,$_[0]) : objectify(1,@_);
1217 return 0 if $x->{sign} !~ /^[+-]$/; # NaN & +-inf aren't
1218 $CALC->_is_even($x->{value});
1223 # return true when arg (BINT or num_str) is positive (>= 0)
1224 # we don't need $self, so undef instead of ref($_[0]) make it slightly faster
1225 my ($self,$x) = ref($_[0]) ? (undef,$_[0]) : objectify(1,@_);
1227 return 1 if $x->{sign} =~ /^\+/;
1233 # return true when arg (BINT or num_str) is negative (< 0)
1234 # we don't need $self, so undef instead of ref($_[0]) make it slightly faster
1235 my ($self,$x) = ref($_[0]) ? (undef,$_[0]) : objectify(1,@_);
1237 return 1 if ($x->{sign} =~ /^-/);
1243 # return true when arg (BINT or num_str) is an integer
1244 # always true for BigInt, but different for Floats
1245 # we don't need $self, so undef instead of ref($_[0]) make it slightly faster
1246 my ($self,$x) = ref($_[0]) ? (undef,$_[0]) : objectify(1,@_);
1248 $x->{sign} =~ /^[+-]$/ ? 1 : 0; # inf/-inf/NaN aren't
1251 ###############################################################################
1255 # multiply two numbers -- stolen from Knuth Vol 2 pg 233
1256 # (BINT or num_str, BINT or num_str) return BINT
1259 my ($self,$x,$y,@r) = (ref($_[0]),@_);
1260 # objectify is costly, so avoid it
1261 if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1])))
1263 ($self,$x,$y,@r) = objectify(2,@_);
1266 return $x if $x->modify('bmul');
1268 return $x->bnan() if (($x->{sign} eq $nan) || ($y->{sign} eq $nan));
1271 if (($x->{sign} =~ /^[+-]inf$/) || ($y->{sign} =~ /^[+-]inf$/))
1273 return $x->bnan() if $x->is_zero() || $y->is_zero();
1274 # result will always be +-inf:
1275 # +inf * +/+inf => +inf, -inf * -/-inf => +inf
1276 # +inf * -/-inf => -inf, -inf * +/+inf => -inf
1277 return $x->binf() if ($x->{sign} =~ /^\+/ && $y->{sign} =~ /^\+/);
1278 return $x->binf() if ($x->{sign} =~ /^-/ && $y->{sign} =~ /^-/);
1279 return $x->binf('-');
1282 return $upgrade->bmul($x,$y,@r)
1283 if defined $upgrade && $y->isa($upgrade);
1285 $r[3] = $y; # no push here
1287 $x->{sign} = $x->{sign} eq $y->{sign} ? '+' : '-'; # +1 * +1 or -1 * -1 => +
1289 $x->{value} = $CALC->_mul($x->{value},$y->{value}); # do actual math
1290 $x->{sign} = '+' if $CALC->_is_zero($x->{value}); # no -0
1292 $x->round(@r) if !exists $x->{_f} || $x->{_f} & MB_NEVER_ROUND == 0;
1298 # helper function that handles +-inf cases for bdiv()/bmod() to reuse code
1299 my ($self,$x,$y) = @_;
1301 # NaN if x == NaN or y == NaN or x==y==0
1302 return wantarray ? ($x->bnan(),$self->bnan()) : $x->bnan()
1303 if (($x->is_nan() || $y->is_nan()) ||
1304 ($x->is_zero() && $y->is_zero()));
1306 # +-inf / +-inf == NaN, reminder also NaN
1307 if (($x->{sign} =~ /^[+-]inf$/) && ($y->{sign} =~ /^[+-]inf$/))
1309 return wantarray ? ($x->bnan(),$self->bnan()) : $x->bnan();
1311 # x / +-inf => 0, remainder x (works even if x == 0)
1312 if ($y->{sign} =~ /^[+-]inf$/)
1314 my $t = $x->copy(); # bzero clobbers up $x
1315 return wantarray ? ($x->bzero(),$t) : $x->bzero()
1318 # 5 / 0 => +inf, -6 / 0 => -inf
1319 # +inf / 0 = inf, inf, and -inf / 0 => -inf, -inf
1320 # exception: -8 / 0 has remainder -8, not 8
1321 # exception: -inf / 0 has remainder -inf, not inf
1324 # +-inf / 0 => special case for -inf
1325 return wantarray ? ($x,$x->copy()) : $x if $x->is_inf();
1326 if (!$x->is_zero() && !$x->is_inf())
1328 my $t = $x->copy(); # binf clobbers up $x
1330 ($x->binf($x->{sign}),$t) : $x->binf($x->{sign})
1334 # last case: +-inf / ordinary number
1336 $sign = '-inf' if substr($x->{sign},0,1) ne $y->{sign};
1338 return wantarray ? ($x,$self->bzero()) : $x;
1343 # (dividend: BINT or num_str, divisor: BINT or num_str) return
1344 # (BINT,BINT) (quo,rem) or BINT (only rem)
1347 my ($self,$x,$y,@r) = (ref($_[0]),@_);
1348 # objectify is costly, so avoid it
1349 if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1])))
1351 ($self,$x,$y,@r) = objectify(2,@_);
1354 return $x if $x->modify('bdiv');
1356 return $self->_div_inf($x,$y)
1357 if (($x->{sign} !~ /^[+-]$/) || ($y->{sign} !~ /^[+-]$/) || $y->is_zero());
1359 return $upgrade->bdiv($upgrade->new($x),$y,@r)
1360 if defined $upgrade && !$y->isa($self);
1362 $r[3] = $y; # no push!
1366 wantarray ? ($x->round(@r),$self->bzero(@r)):$x->round(@r) if $x->is_zero();
1368 # Is $x in the interval [0, $y) (aka $x <= $y) ?
1369 my $cmp = $CALC->_acmp($x->{value},$y->{value});
1370 if (($cmp < 0) and (($x->{sign} eq $y->{sign}) or !wantarray))
1372 return $upgrade->bdiv($upgrade->new($x),$upgrade->new($y),@r)
1373 if defined $upgrade;
1375 return $x->bzero()->round(@r) unless wantarray;
1376 my $t = $x->copy(); # make copy first, because $x->bzero() clobbers $x
1377 return ($x->bzero()->round(@r),$t);
1381 # shortcut, both are the same, so set to +/- 1
1382 $x->__one( ($x->{sign} ne $y->{sign} ? '-' : '+') );
1383 return $x unless wantarray;
1384 return ($x->round(@r),$self->bzero(@r));
1386 return $upgrade->bdiv($upgrade->new($x),$upgrade->new($y),@r)
1387 if defined $upgrade;
1389 # calc new sign and in case $y == +/- 1, return $x
1390 my $xsign = $x->{sign}; # keep
1391 $x->{sign} = ($x->{sign} ne $y->{sign} ? '-' : '+');
1392 # check for / +-1 (cant use $y->is_one due to '-'
1393 if ($CALC->_is_one($y->{value}))
1395 return wantarray ? ($x->round(@r),$self->bzero(@r)) : $x->round(@r);
1400 my $rem = $self->bzero();
1401 ($x->{value},$rem->{value}) = $CALC->_div($x->{value},$y->{value});
1402 $x->{sign} = '+' if $CALC->_is_zero($x->{value});
1403 $rem->{_a} = $x->{_a};
1404 $rem->{_p} = $x->{_p};
1406 if (! $CALC->_is_zero($rem->{value}))
1408 $rem->{sign} = $y->{sign};
1409 $rem = $y-$rem if $xsign ne $y->{sign}; # one of them '-'
1413 $rem->{sign} = '+'; # dont leave -0
1415 return ($x,$rem->round(@r));
1418 $x->{value} = $CALC->_div($x->{value},$y->{value});
1419 $x->{sign} = '+' if $CALC->_is_zero($x->{value});
1421 $x->round(@r) if !exists $x->{_f} || $x->{_f} & MB_NEVER_ROUND == 0;
1425 ###############################################################################
1430 # modulus (or remainder)
1431 # (BINT or num_str, BINT or num_str) return BINT
1434 my ($self,$x,$y,@r) = (ref($_[0]),@_);
1435 # objectify is costly, so avoid it
1436 if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1])))
1438 ($self,$x,$y,@r) = objectify(2,@_);
1441 return $x if $x->modify('bmod');
1442 $r[3] = $y; # no push!
1443 if (($x->{sign} !~ /^[+-]$/) || ($y->{sign} !~ /^[+-]$/) || $y->is_zero())
1445 my ($d,$r) = $self->_div_inf($x,$y);
1446 $x->{sign} = $r->{sign};
1447 $x->{value} = $r->{value};
1448 return $x->round(@r);
1451 if ($CALC->can('_mod'))
1453 # calc new sign and in case $y == +/- 1, return $x
1454 $x->{value} = $CALC->_mod($x->{value},$y->{value});
1455 if (!$CALC->_is_zero($x->{value}))
1457 my $xsign = $x->{sign};
1458 $x->{sign} = $y->{sign};
1459 if ($xsign ne $y->{sign})
1461 my $t = $CALC->_copy($x->{value}); # copy $x
1462 $x->{value} = $CALC->_copy($y->{value}); # copy $y to $x
1463 $x->{value} = $CALC->_sub($y->{value},$t,1); # $y-$x
1468 $x->{sign} = '+'; # dont leave -0
1470 $x->round(@r) if !exists $x->{_f} || $x->{_f} & MB_NEVER_ROUND == 0;
1473 my ($t,$rem) = $self->bdiv($x->copy(),$y,@r); # slow way (also rounds)
1475 foreach (qw/value sign _a _p/)
1477 $x->{$_} = $rem->{$_};
1484 # modular inverse. given a number which is (hopefully) relatively
1485 # prime to the modulus, calculate its inverse using Euclid's
1486 # alogrithm. if the number is not relatively prime to the modulus
1487 # (i.e. their gcd is not one) then NaN is returned.
1490 my ($self,$x,$y,@r) = (ref($_[0]),@_);
1491 # objectify is costly, so avoid it
1492 if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1])))
1494 ($self,$x,$y,@r) = objectify(2,@_);
1497 return $x if $x->modify('bmodinv');
1500 if ($y->{sign} ne '+' # -, NaN, +inf, -inf
1501 || $x->is_zero() # or num == 0
1502 || $x->{sign} !~ /^[+-]$/ # or num NaN, inf, -inf
1505 # put least residue into $x if $x was negative, and thus make it positive
1506 $x->bmod($y) if $x->{sign} eq '-';
1508 if ($CALC->can('_modinv'))
1510 $x->{value} = $CALC->_modinv($x->{value},$y->{value});
1511 $x->bnan() if !defined $x->{value} ; # in case there was none
1515 my ($u, $u1) = ($self->bzero(), $self->bone());
1516 my ($a, $b) = ($y->copy(), $x->copy());
1518 # first step need always be done since $num (and thus $b) is never 0
1519 # Note that the loop is aligned so that the check occurs between #2 and #1
1520 # thus saving us one step #2 at the loop end. Typical loop count is 1. Even
1521 # a case with 28 loops still gains about 3% with this layout.
1523 ($a, $q, $b) = ($b, $a->bdiv($b)); # step #1
1524 # Euclid's Algorithm
1525 while (!$b->is_zero())
1527 ($u, $u1) = ($u1, $u->bsub($u1->copy()->bmul($q))); # step #2
1528 ($a, $q, $b) = ($b, $a->bdiv($b)); # step #1 again
1531 # if the gcd is not 1, then return NaN! It would be pointless to
1532 # have called bgcd to check this first, because we would then be performing
1533 # the same Euclidean Algorithm *twice*
1534 return $x->bnan() unless $a->is_one();
1537 $x->{value} = $u1->{value};
1538 $x->{sign} = $u1->{sign};
1544 # takes a very large number to a very large exponent in a given very
1545 # large modulus, quickly, thanks to binary exponentation. supports
1546 # negative exponents.
1547 my ($self,$num,$exp,$mod,@r) = objectify(3,@_);
1549 return $num if $num->modify('bmodpow');
1551 # check modulus for valid values
1552 return $num->bnan() if ($mod->{sign} ne '+' # NaN, - , -inf, +inf
1553 || $mod->is_zero());
1555 # check exponent for valid values
1556 if ($exp->{sign} =~ /\w/)
1558 # i.e., if it's NaN, +inf, or -inf...
1559 return $num->bnan();
1562 $num->bmodinv ($mod) if ($exp->{sign} eq '-');
1564 # check num for valid values (also NaN if there was no inverse but $exp < 0)
1565 return $num->bnan() if $num->{sign} !~ /^[+-]$/;
1567 if ($CALC->can('_modpow'))
1569 # $mod is positive, sign on $exp is ignored, result also positive
1570 $num->{value} = $CALC->_modpow($num->{value},$exp->{value},$mod->{value});
1574 # in the trivial case,
1575 return $num->bzero(@r) if $mod->is_one();
1576 return $num->bone('+',@r) if $num->is_zero() or $num->is_one();
1578 # $num->bmod($mod); # if $x is large, make it smaller first
1579 my $acc = $num->copy(); # but this is not really faster...
1581 $num->bone(); # keep ref to $num
1583 my $expbin = $exp->as_bin(); $expbin =~ s/^[-]?0b//; # ignore sign and prefix
1584 my $len = length($expbin);
1587 if( substr($expbin,$len,1) eq '1')
1589 $num->bmul($acc)->bmod($mod);
1591 $acc->bmul($acc)->bmod($mod);
1597 ###############################################################################
1601 # (BINT or num_str, BINT or num_str) return BINT
1602 # compute factorial numbers
1603 # modifies first argument
1604 my ($self,$x,@r) = ref($_[0]) ? (ref($_[0]),@_) : objectify(1,@_);
1606 return $x if $x->modify('bfac');
1608 return $x->bnan() if $x->{sign} ne '+'; # inf, NnN, <0 etc => NaN
1609 return $x->bone('+',@r) if $x->is_zero() || $x->is_one(); # 0 or 1 => 1
1611 if ($CALC->can('_fac'))
1613 $x->{value} = $CALC->_fac($x->{value});
1614 return $x->round(@r);
1619 # seems we need not to temp. clear A/P of $x since the result is the same
1620 my $f = $self->new(2);
1621 while ($f->bacmp($n) < 0)
1623 $x->bmul($f); $f->binc();
1625 $x->bmul($f,@r); # last step and also round
1630 # (BINT or num_str, BINT or num_str) return BINT
1631 # compute power of two numbers -- stolen from Knuth Vol 2 pg 233
1632 # modifies first argument
1635 my ($self,$x,$y,@r) = (ref($_[0]),@_);
1636 # objectify is costly, so avoid it
1637 if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1])))
1639 ($self,$x,$y,@r) = objectify(2,@_);
1642 return $x if $x->modify('bpow');
1644 return $upgrade->bpow($upgrade->new($x),$y,@r)
1645 if defined $upgrade && !$y->isa($self);
1647 $r[3] = $y; # no push!
1648 return $x if $x->{sign} =~ /^[+-]inf$/; # -inf/+inf ** x
1649 return $x->bnan() if $x->{sign} eq $nan || $y->{sign} eq $nan;
1650 return $x->bone('+',@r) if $y->is_zero();
1651 return $x->round(@r) if $x->is_one() || $y->is_one();
1652 if ($x->{sign} eq '-' && $CALC->_is_one($x->{value}))
1654 # if $x == -1 and odd/even y => +1/-1
1655 return $y->is_odd() ? $x->round(@r) : $x->babs()->round(@r);
1656 # my Casio FX-5500L has a bug here: -1 ** 2 is -1, but -1 * -1 is 1;
1658 # 1 ** -y => 1 / (1 ** |y|)
1659 # so do test for negative $y after above's clause
1660 return $x->bnan() if $y->{sign} eq '-';
1661 return $x->round(@r) if $x->is_zero(); # 0**y => 0 (if not y <= 0)
1663 if ($CALC->can('_pow'))
1665 $x->{value} = $CALC->_pow($x->{value},$y->{value});
1666 $x->round(@r) if !exists $x->{_f} || $x->{_f} & MB_NEVER_ROUND == 0;
1670 # based on the assumption that shifting in base 10 is fast, and that mul
1671 # works faster if numbers are small: we count trailing zeros (this step is
1672 # O(1)..O(N), but in case of O(N) we save much more time due to this),
1673 # stripping them out of the multiplication, and add $count * $y zeros
1674 # afterwards like this:
1675 # 300 ** 3 == 300*300*300 == 3*3*3 . '0' x 2 * 3 == 27 . '0' x 6
1676 # creates deep recursion since brsft/blsft use bpow sometimes.
1677 # my $zeros = $x->_trailing_zeros();
1680 # $x->brsft($zeros,10); # remove zeros
1681 # $x->bpow($y); # recursion (will not branch into here again)
1682 # $zeros = $y * $zeros; # real number of zeros to add
1683 # $x->blsft($zeros,10);
1684 # return $x->round(@r);
1687 my $pow2 = $self->__one();
1688 my $y_bin = $y->as_bin(); $y_bin =~ s/^0b//;
1689 my $len = length($y_bin);
1692 $pow2->bmul($x) if substr($y_bin,$len,1) eq '1'; # is odd?
1696 $x->round(@r) if !exists $x->{_f} || $x->{_f} & MB_NEVER_ROUND == 0;
1702 # (BINT or num_str, BINT or num_str) return BINT
1703 # compute x << y, base n, y >= 0
1706 my ($self,$x,$y,$n,@r) = (ref($_[0]),@_);
1707 # objectify is costly, so avoid it
1708 if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1])))
1710 ($self,$x,$y,$n,@r) = objectify(2,@_);
1713 return $x if $x->modify('blsft');
1714 return $x->bnan() if ($x->{sign} !~ /^[+-]$/ || $y->{sign} !~ /^[+-]$/);
1715 return $x->round(@r) if $y->is_zero();
1717 $n = 2 if !defined $n; return $x->bnan() if $n <= 0 || $y->{sign} eq '-';
1719 my $t; $t = $CALC->_lsft($x->{value},$y->{value},$n) if $CALC->can('_lsft');
1722 $x->{value} = $t; return $x->round(@r);
1725 return $x->bmul( $self->bpow($n, $y, @r), @r );
1730 # (BINT or num_str, BINT or num_str) return BINT
1731 # compute x >> y, base n, y >= 0
1734 my ($self,$x,$y,$n,@r) = (ref($_[0]),@_);
1735 # objectify is costly, so avoid it
1736 if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1])))
1738 ($self,$x,$y,$n,@r) = objectify(2,@_);
1741 return $x if $x->modify('brsft');
1742 return $x->bnan() if ($x->{sign} !~ /^[+-]$/ || $y->{sign} !~ /^[+-]$/);
1743 return $x->round(@r) if $y->is_zero();
1744 return $x->bzero(@r) if $x->is_zero(); # 0 => 0
1746 $n = 2 if !defined $n; return $x->bnan() if $n <= 0 || $y->{sign} eq '-';
1748 # this only works for negative numbers when shifting in base 2
1749 if (($x->{sign} eq '-') && ($n == 2))
1751 return $x->round(@r) if $x->is_one('-'); # -1 => -1
1754 # although this is O(N*N) in calc (as_bin!) it is O(N) in Pari et al
1755 # but perhaps there is a better emulation for two's complement shift...
1756 # if $y != 1, we must simulate it by doing:
1757 # convert to bin, flip all bits, shift, and be done
1758 $x->binc(); # -3 => -2
1759 my $bin = $x->as_bin();
1760 $bin =~ s/^-0b//; # strip '-0b' prefix
1761 $bin =~ tr/10/01/; # flip bits
1763 if (CORE::length($bin) <= $y)
1765 $bin = '0'; # shifting to far right creates -1
1766 # 0, because later increment makes
1767 # that 1, attached '-' makes it '-1'
1768 # because -1 >> x == -1 !
1772 $bin =~ s/.{$y}$//; # cut off at the right side
1773 $bin = '1' . $bin; # extend left side by one dummy '1'
1774 $bin =~ tr/10/01/; # flip bits back
1776 my $res = $self->new('0b'.$bin); # add prefix and convert back
1777 $res->binc(); # remember to increment
1778 $x->{value} = $res->{value}; # take over value
1779 return $x->round(@r); # we are done now, magic, isn't?
1781 $x->bdec(); # n == 2, but $y == 1: this fixes it
1784 my $t; $t = $CALC->_rsft($x->{value},$y->{value},$n) if $CALC->can('_rsft');
1788 return $x->round(@r);
1791 $x->bdiv($self->bpow($n,$y, @r), @r);
1797 #(BINT or num_str, BINT or num_str) return BINT
1801 my ($self,$x,$y,@r) = (ref($_[0]),@_);
1802 # objectify is costly, so avoid it
1803 if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1])))
1805 ($self,$x,$y,@r) = objectify(2,@_);
1808 return $x if $x->modify('band');
1810 $r[3] = $y; # no push!
1811 local $Math::BigInt::upgrade = undef;
1813 return $x->bnan() if ($x->{sign} !~ /^[+-]$/ || $y->{sign} !~ /^[+-]$/);
1814 return $x->bzero(@r) if $y->is_zero() || $x->is_zero();
1816 my $sign = 0; # sign of result
1817 $sign = 1 if ($x->{sign} eq '-') && ($y->{sign} eq '-');
1818 my $sx = 1; $sx = -1 if $x->{sign} eq '-';
1819 my $sy = 1; $sy = -1 if $y->{sign} eq '-';
1821 if ($CALC->can('_and') && $sx == 1 && $sy == 1)
1823 $x->{value} = $CALC->_and($x->{value},$y->{value});
1824 return $x->round(@r);
1827 my $m = $self->bone(); my ($xr,$yr);
1828 my $x10000 = $self->new (0x1000);
1829 my $y1 = copy(ref($x),$y); # make copy
1830 $y1->babs(); # and positive
1831 my $x1 = $x->copy()->babs(); $x->bzero(); # modify x in place!
1832 use integer; # need this for negative bools
1833 while (!$x1->is_zero() && !$y1->is_zero())
1835 ($x1, $xr) = bdiv($x1, $x10000);
1836 ($y1, $yr) = bdiv($y1, $x10000);
1837 # make both op's numbers!
1838 $x->badd( bmul( $class->new(
1839 abs($sx*int($xr->numify()) & $sy*int($yr->numify()))),
1843 $x->bneg() if $sign;
1849 #(BINT or num_str, BINT or num_str) return BINT
1853 my ($self,$x,$y,@r) = (ref($_[0]),@_);
1854 # objectify is costly, so avoid it
1855 if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1])))
1857 ($self,$x,$y,@r) = objectify(2,@_);
1860 return $x if $x->modify('bior');
1861 $r[3] = $y; # no push!
1863 local $Math::BigInt::upgrade = undef;
1865 return $x->bnan() if ($x->{sign} !~ /^[+-]$/ || $y->{sign} !~ /^[+-]$/);
1866 return $x->round(@r) if $y->is_zero();
1868 my $sign = 0; # sign of result
1869 $sign = 1 if ($x->{sign} eq '-') || ($y->{sign} eq '-');
1870 my $sx = 1; $sx = -1 if $x->{sign} eq '-';
1871 my $sy = 1; $sy = -1 if $y->{sign} eq '-';
1873 # don't use lib for negative values
1874 if ($CALC->can('_or') && $sx == 1 && $sy == 1)
1876 $x->{value} = $CALC->_or($x->{value},$y->{value});
1877 return $x->round(@r);
1880 my $m = $self->bone(); my ($xr,$yr);
1881 my $x10000 = $self->new(0x10000);
1882 my $y1 = copy(ref($x),$y); # make copy
1883 $y1->babs(); # and positive
1884 my $x1 = $x->copy()->babs(); $x->bzero(); # modify x in place!
1885 use integer; # need this for negative bools
1886 while (!$x1->is_zero() || !$y1->is_zero())
1888 ($x1, $xr) = bdiv($x1,$x10000);
1889 ($y1, $yr) = bdiv($y1,$x10000);
1890 # make both op's numbers!
1891 $x->badd( bmul( $class->new(
1892 abs($sx*int($xr->numify()) | $sy*int($yr->numify()))),
1896 $x->bneg() if $sign;
1902 #(BINT or num_str, BINT or num_str) return BINT
1906 my ($self,$x,$y,@r) = (ref($_[0]),@_);
1907 # objectify is costly, so avoid it
1908 if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1])))
1910 ($self,$x,$y,@r) = objectify(2,@_);
1913 return $x if $x->modify('bxor');
1914 $r[3] = $y; # no push!
1916 local $Math::BigInt::upgrade = undef;
1918 return $x->bnan() if ($x->{sign} !~ /^[+-]$/ || $y->{sign} !~ /^[+-]$/);
1919 return $x->round(@r) if $y->is_zero();
1921 my $sign = 0; # sign of result
1922 $sign = 1 if $x->{sign} ne $y->{sign};
1923 my $sx = 1; $sx = -1 if $x->{sign} eq '-';
1924 my $sy = 1; $sy = -1 if $y->{sign} eq '-';
1926 # don't use lib for negative values
1927 if ($CALC->can('_xor') && $sx == 1 && $sy == 1)
1929 $x->{value} = $CALC->_xor($x->{value},$y->{value});
1930 return $x->round(@r);
1933 my $m = $self->bone(); my ($xr,$yr);
1934 my $x10000 = $self->new(0x10000);
1935 my $y1 = copy(ref($x),$y); # make copy
1936 $y1->babs(); # and positive
1937 my $x1 = $x->copy()->babs(); $x->bzero(); # modify x in place!
1938 use integer; # need this for negative bools
1939 while (!$x1->is_zero() || !$y1->is_zero())
1941 ($x1, $xr) = bdiv($x1, $x10000);
1942 ($y1, $yr) = bdiv($y1, $x10000);
1943 # make both op's numbers!
1944 $x->badd( bmul( $class->new(
1945 abs($sx*int($xr->numify()) ^ $sy*int($yr->numify()))),
1949 $x->bneg() if $sign;
1955 my ($self,$x) = ref($_[0]) ? (ref($_[0]),$_[0]) : objectify(1,@_);
1957 my $e = $CALC->_len($x->{value});
1958 return wantarray ? ($e,0) : $e;
1963 # return the nth decimal digit, negative values count backward, 0 is right
1964 my ($self,$x,$n) = ref($_[0]) ? (ref($_[0]),@_) : objectify(1,@_);
1966 $CALC->_digit($x->{value},$n||0);
1971 # return the amount of trailing zeros in $x
1973 $x = $class->new($x) unless ref $x;
1975 return 0 if $x->is_zero() || $x->is_odd() || $x->{sign} !~ /^[+-]$/;
1977 return $CALC->_zeros($x->{value}) if $CALC->can('_zeros');
1979 # if not: since we do not know underlying internal representation:
1980 my $es = "$x"; $es =~ /([0]*)$/;
1981 return 0 if !defined $1; # no zeros
1982 CORE::length("$1"); # as string, not as +0!
1987 my ($self,$x,@r) = ref($_[0]) ? (ref($_[0]),@_) : objectify(1,@_);
1989 return $x if $x->modify('bsqrt');
1991 return $x->bnan() if $x->{sign} ne '+'; # -x or inf or NaN => NaN
1992 return $x->bzero(@r) if $x->is_zero(); # 0 => 0
1993 return $x->round(@r) if $x->is_one(); # 1 => 1
1995 return $upgrade->bsqrt($x,@r) if defined $upgrade;
1997 if ($CALC->can('_sqrt'))
1999 $x->{value} = $CALC->_sqrt($x->{value});
2000 return $x->round(@r);
2003 return $x->bone('+',@r) if $x < 4; # 2,3 => 1
2005 my $l = int($x->length()/2);
2007 $x->bone(); # keep ref($x), but modify it
2010 my $last = $self->bzero();
2011 my $two = $self->new(2);
2012 my $lastlast = $x+$two;
2013 while ($last != $x && $lastlast != $x)
2015 $lastlast = $last; $last = $x;
2019 $x-- if $x * $x > $y; # overshot?
2025 # return a copy of the exponent (here always 0, NaN or 1 for $m == 0)
2026 my ($self,$x) = ref($_[0]) ? (ref($_[0]),$_[0]) : objectify(1,@_);
2028 if ($x->{sign} !~ /^[+-]$/)
2030 my $s = $x->{sign}; $s =~ s/^[+-]//;
2031 return $self->new($s); # -inf,+inf => inf
2033 my $e = $class->bzero();
2034 return $e->binc() if $x->is_zero();
2035 $e += $x->_trailing_zeros();
2041 # return the mantissa (compatible to Math::BigFloat, e.g. reduced)
2042 my ($self,$x) = ref($_[0]) ? (ref($_[0]),$_[0]) : objectify(1,@_);
2044 if ($x->{sign} !~ /^[+-]$/)
2046 return $self->new($x->{sign}); # keep + or - sign
2049 # that's inefficient
2050 my $zeros = $m->_trailing_zeros();
2051 $m->brsft($zeros,10) if $zeros != 0;
2057 # return a copy of both the exponent and the mantissa
2058 my ($self,$x) = ref($_[0]) ? (ref($_[0]),$_[0]) : objectify(1,@_);
2060 return ($x->mantissa(),$x->exponent());
2063 ##############################################################################
2064 # rounding functions
2068 # precision: round to the $Nth digit left (+$n) or right (-$n) from the '.'
2069 # $n == 0 || $n == 1 => round to integer
2070 my $x = shift; $x = $class->new($x) unless ref $x;
2071 my ($scale,$mode) = $x->_scale_p($x->precision(),$x->round_mode(),@_);
2072 return $x if !defined $scale; # no-op
2073 return $x if $x->modify('bfround');
2075 # no-op for BigInts if $n <= 0
2078 $x->{_a} = undef; # clear an eventual set A
2079 $x->{_p} = $scale; return $x;
2082 $x->bround( $x->length()-$scale, $mode);
2083 $x->{_a} = undef; # bround sets {_a}
2084 $x->{_p} = $scale; # so correct it
2088 sub _scan_for_nonzero
2094 my $len = $x->length();
2095 return 0 if $len == 1; # '5' is trailed by invisible zeros
2096 my $follow = $pad - 1;
2097 return 0 if $follow > $len || $follow < 1;
2099 # since we do not know underlying represention of $x, use decimal string
2100 #my $r = substr ($$xs,-$follow);
2101 my $r = substr ("$x",-$follow);
2102 return 1 if $r =~ /[^0]/;
2108 # to make life easier for switch between MBF and MBI (autoload fxxx()
2109 # like MBF does for bxxx()?)
2111 return $x->bround(@_);
2116 # accuracy: +$n preserve $n digits from left,
2117 # -$n preserve $n digits from right (f.i. for 0.1234 style in MBF)
2119 # and overwrite the rest with 0's, return normalized number
2120 # do not return $x->bnorm(), but $x
2122 my $x = shift; $x = $class->new($x) unless ref $x;
2123 my ($scale,$mode) = $x->_scale_a($x->accuracy(),$x->round_mode(),@_);
2124 return $x if !defined $scale; # no-op
2125 return $x if $x->modify('bround');
2127 if ($x->is_zero() || $scale == 0)
2129 $x->{_a} = $scale if !defined $x->{_a} || $x->{_a} > $scale; # 3 > 2
2132 return $x if $x->{sign} !~ /^[+-]$/; # inf, NaN
2134 # we have fewer digits than we want to scale to
2135 my $len = $x->length();
2136 # scale < 0, but > -len (not >=!)
2137 if (($scale < 0 && $scale < -$len-1) || ($scale >= $len))
2139 $x->{_a} = $scale if !defined $x->{_a} || $x->{_a} > $scale; # 3 > 2
2143 # count of 0's to pad, from left (+) or right (-): 9 - +6 => 3, or |-6| => 6
2144 my ($pad,$digit_round,$digit_after);
2145 $pad = $len - $scale;
2146 $pad = abs($scale-1) if $scale < 0;
2148 # do not use digit(), it is costly for binary => decimal
2150 my $xs = $CALC->_str($x->{value});
2153 # pad: 123: 0 => -1, at 1 => -2, at 2 => -3, at 3 => -4
2154 # pad+1: 123: 0 => 0, at 1 => -1, at 2 => -2, at 3 => -3
2155 $digit_round = '0'; $digit_round = substr($$xs,$pl,1) if $pad <= $len;
2156 $pl++; $pl ++ if $pad >= $len;
2157 $digit_after = '0'; $digit_after = substr($$xs,$pl,1) if $pad > 0;
2159 # in case of 01234 we round down, for 6789 up, and only in case 5 we look
2160 # closer at the remaining digits of the original $x, remember decision
2161 my $round_up = 1; # default round up
2163 ($mode eq 'trunc') || # trunc by round down
2164 ($digit_after =~ /[01234]/) || # round down anyway,
2166 ($digit_after eq '5') && # not 5000...0000
2167 ($x->_scan_for_nonzero($pad,$xs) == 0) &&
2169 ($mode eq 'even') && ($digit_round =~ /[24680]/) ||
2170 ($mode eq 'odd') && ($digit_round =~ /[13579]/) ||
2171 ($mode eq '+inf') && ($x->{sign} eq '-') ||
2172 ($mode eq '-inf') && ($x->{sign} eq '+') ||
2173 ($mode eq 'zero') # round down if zero, sign adjusted below
2175 my $put_back = 0; # not yet modified
2177 if (($pad > 0) && ($pad <= $len))
2179 substr($$xs,-$pad,$pad) = '0' x $pad;
2184 $x->bzero(); # round to '0'
2187 if ($round_up) # what gave test above?
2190 $pad = $len, $$xs = '0'x$pad if $scale < 0; # tlr: whack 0.51=>1.0
2192 # we modify directly the string variant instead of creating a number and
2193 # adding it, since that is faster (we already have the string)
2194 my $c = 0; $pad ++; # for $pad == $len case
2195 while ($pad <= $len)
2197 $c = substr($$xs,-$pad,1) + 1; $c = '0' if $c eq '10';
2198 substr($$xs,-$pad,1) = $c; $pad++;
2199 last if $c != 0; # no overflow => early out
2201 $$xs = '1'.$$xs if $c == 0;
2204 $x->{value} = $CALC->_new($xs) if $put_back == 1; # put back in if needed
2206 $x->{_a} = $scale if $scale >= 0;
2209 $x->{_a} = $len+$scale;
2210 $x->{_a} = 0 if $scale < -$len;
2217 # return integer less or equal then number, since it is already integer,
2218 # always returns $self
2219 my ($self,$x,@r) = ref($_[0]) ? (ref($_[0]),@_) : objectify(1,@_);
2226 # return integer greater or equal then number, since it is already integer,
2227 # always returns $self
2228 my ($self,$x,@r) = ref($_[0]) ? (ref($_[0]),@_) : objectify(1,@_);
2233 ##############################################################################
2234 # private stuff (internal use only)
2238 # internal speedup, set argument to 1, or create a +/- 1
2240 my $x = $self->bone(); # $x->{value} = $CALC->_one();
2241 $x->{sign} = shift || '+';
2247 # Overload will swap params if first one is no object ref so that the first
2248 # one is always an object ref. In this case, third param is true.
2249 # This routine is to overcome the effect of scalar,$object creating an object
2250 # of the class of this package, instead of the second param $object. This
2251 # happens inside overload, when the overload section of this package is
2252 # inherited by sub classes.
2253 # For overload cases (and this is used only there), we need to preserve the
2254 # args, hence the copy().
2255 # You can override this method in a subclass, the overload section will call
2256 # $object->_swap() to make sure it arrives at the proper subclass, with some
2257 # exceptions like '+' and '-'. To make '+' and '-' work, you also need to
2258 # specify your own overload for them.
2260 # object, (object|scalar) => preserve first and make copy
2261 # scalar, object => swapped, re-swap and create new from first
2262 # (using class of second object, not $class!!)
2263 my $self = shift; # for override in subclass
2266 my $c = ref ($_[0]) || $class; # fallback $class should not happen
2267 return ( $c->new($_[1]), $_[0] );
2269 return ( $_[0]->copy(), $_[1] );
2274 # check for strings, if yes, return objects instead
2276 # the first argument is number of args objectify() should look at it will
2277 # return $count+1 elements, the first will be a classname. This is because
2278 # overloaded '""' calls bstr($object,undef,undef) and this would result in
2279 # useless objects beeing created and thrown away. So we cannot simple loop
2280 # over @_. If the given count is 0, all arguments will be used.
2282 # If the second arg is a ref, use it as class.
2283 # If not, try to use it as classname, unless undef, then use $class
2284 # (aka Math::BigInt). The latter shouldn't happen,though.
2287 # $x->badd(1); => ref x, scalar y
2288 # Class->badd(1,2); => classname x (scalar), scalar x, scalar y
2289 # Class->badd( Class->(1),2); => classname x (scalar), ref x, scalar y
2290 # Math::BigInt::badd(1,2); => scalar x, scalar y
2291 # In the last case we check number of arguments to turn it silently into
2292 # $class,1,2. (We can not take '1' as class ;o)
2293 # badd($class,1) is not supported (it should, eventually, try to add undef)
2294 # currently it tries 'Math::BigInt' + 1, which will not work.
2296 # some shortcut for the common cases
2298 return (ref($_[1]),$_[1]) if (@_ == 2) && ($_[0]||0 == 1) && ref($_[1]);
2300 my $count = abs(shift || 0);
2302 my (@a,$k,$d); # resulting array, temp, and downgrade
2305 # okay, got object as first
2310 # nope, got 1,2 (Class->xxx(1) => Class,1 and not supported)
2312 $a[0] = shift if $_[0] =~ /^[A-Z].*::/; # classname as first?
2316 # disable downgrading, because Math::BigFLoat->foo('1.0','2.0') needs floats
2317 if (defined ${"$a[0]::downgrade"})
2319 $d = ${"$a[0]::downgrade"};
2320 ${"$a[0]::downgrade"} = undef;
2323 my $up = ${"$a[0]::upgrade"};
2324 # print "Now in objectify, my class is today $a[0]\n";
2332 $k = $a[0]->new($k);
2334 elsif (!defined $up && ref($k) ne $a[0])
2336 # foreign object, try to convert to integer
2337 $k->can('as_number') ? $k = $k->as_number() : $k = $a[0]->new($k);
2350 $k = $a[0]->new($k);
2352 elsif (!defined $up && ref($k) ne $a[0])
2354 # foreign object, try to convert to integer
2355 $k->can('as_number') ? $k = $k->as_number() : $k = $a[0]->new($k);
2359 push @a,@_; # return other params, too
2361 die "$class objectify needs list context" unless wantarray;
2362 ${"$a[0]::downgrade"} = $d;
2371 my @a; my $l = scalar @_;
2372 for ( my $i = 0; $i < $l ; $i++ )
2374 if ($_[$i] eq ':constant')
2376 # this causes overlord er load to step in
2377 overload::constant integer => sub { $self->new(shift) };
2378 overload::constant binary => sub { $self->new(shift) };
2380 elsif ($_[$i] eq 'upgrade')
2382 # this causes upgrading
2383 $upgrade = $_[$i+1]; # or undef to disable
2386 elsif ($_[$i] =~ /^lib$/i)
2388 # this causes a different low lib to take care...
2389 $CALC = $_[$i+1] || '';
2397 # any non :constant stuff is handled by our parent, Exporter
2398 # even if @_ is empty, to give it a chance
2399 $self->SUPER::import(@a); # need it for subclasses
2400 $self->export_to_level(1,$self,@a); # need it for MBF
2402 # try to load core math lib
2403 my @c = split /\s*,\s*/,$CALC;
2404 push @c,'Calc'; # if all fail, try this
2405 $CALC = ''; # signal error
2406 foreach my $lib (@c)
2408 next if ($lib || '') eq '';
2409 $lib = 'Math::BigInt::'.$lib if $lib !~ /^Math::BigInt/i;
2413 # Perl < 5.6.0 dies with "out of memory!" when eval() and ':constant' is
2414 # used in the same script, or eval inside import().
2415 my @parts = split /::/, $lib; # Math::BigInt => Math BigInt
2416 my $file = pop @parts; $file .= '.pm'; # BigInt => BigInt.pm
2418 $file = File::Spec->catfile (@parts, $file);
2419 eval { require "$file"; $lib->import( @c ); }
2423 eval "use $lib qw/@c/;";
2425 $CALC = $lib, last if $@ eq ''; # no error in loading lib?
2427 die "Couldn't load any math lib, not even the default" if $CALC eq '';
2432 # convert a (ref to) big hex string to BigInt, return undef for error
2435 my $x = Math::BigInt->bzero();
2438 $$hs =~ s/([0-9a-fA-F])_([0-9a-fA-F])/$1$2/g;
2439 $$hs =~ s/([0-9a-fA-F])_([0-9a-fA-F])/$1$2/g;
2441 return $x->bnan() if $$hs !~ /^[\-\+]?0x[0-9A-Fa-f]+$/;
2443 my $sign = '+'; $sign = '-' if ($$hs =~ /^-/);
2445 $$hs =~ s/^[+-]//; # strip sign
2446 if ($CALC->can('_from_hex'))
2448 $x->{value} = $CALC->_from_hex($hs);
2452 # fallback to pure perl
2453 my $mul = Math::BigInt->bzero(); $mul++;
2454 my $x65536 = Math::BigInt->new(65536);
2455 my $len = CORE::length($$hs)-2;
2456 $len = int($len/4); # 4-digit parts, w/o '0x'
2457 my $val; my $i = -4;
2460 $val = substr($$hs,$i,4);
2461 $val =~ s/^[+-]?0x// if $len == 0; # for last part only because
2462 $val = hex($val); # hex does not like wrong chars
2464 $x += $mul * $val if $val != 0;
2465 $mul *= $x65536 if $len >= 0; # skip last mul
2468 $x->{sign} = $sign unless $CALC->_is_zero($x->{value}); # no '-0'
2474 # convert a (ref to) big binary string to BigInt, return undef for error
2477 my $x = Math::BigInt->bzero();
2479 $$bs =~ s/([01])_([01])/$1$2/g;
2480 $$bs =~ s/([01])_([01])/$1$2/g;
2481 return $x->bnan() if $$bs !~ /^[+-]?0b[01]+$/;
2483 my $sign = '+'; $sign = '-' if ($$bs =~ /^\-/);
2484 $$bs =~ s/^[+-]//; # strip sign
2485 if ($CALC->can('_from_bin'))
2487 $x->{value} = $CALC->_from_bin($bs);
2491 my $mul = Math::BigInt->bzero(); $mul++;
2492 my $x256 = Math::BigInt->new(256);
2493 my $len = CORE::length($$bs)-2;
2494 $len = int($len/8); # 8-digit parts, w/o '0b'
2495 my $val; my $i = -8;
2498 $val = substr($$bs,$i,8);
2499 $val =~ s/^[+-]?0b// if $len == 0; # for last part only
2500 #$val = oct('0b'.$val); # does not work on Perl prior to 5.6.0
2502 # $val = ('0' x (8-CORE::length($val))).$val if CORE::length($val) < 8;
2503 $val = ord(pack('B8',substr('00000000'.$val,-8,8)));
2505 $x += $mul * $val if $val != 0;
2506 $mul *= $x256 if $len >= 0; # skip last mul
2509 $x->{sign} = $sign unless $CALC->_is_zero($x->{value}); # no '-0'
2515 # (ref to num_str) return num_str
2516 # internal, take apart a string and return the pieces
2517 # strip leading/trailing whitespace, leading zeros, underscore and reject
2521 # strip white space at front, also extranous leading zeros
2522 $$x =~ s/^\s*([-]?)0*([0-9])/$1$2/g; # will not strip ' .2'
2523 $$x =~ s/^\s+//; # but this will
2524 $$x =~ s/\s+$//g; # strip white space at end
2526 # shortcut, if nothing to split, return early
2527 if ($$x =~ /^[+-]?\d+\z/)
2529 $$x =~ s/^([+-])0*([0-9])/$2/; my $sign = $1 || '+';
2530 return (\$sign, $x, \'', \'', \0);
2533 # invalid starting char?
2534 return if $$x !~ /^[+-]?(\.?[0-9]|0b[0-1]|0x[0-9a-fA-F])/;
2536 return __from_hex($x) if $$x =~ /^[\-\+]?0x/; # hex string
2537 return __from_bin($x) if $$x =~ /^[\-\+]?0b/; # binary string
2539 # strip underscores between digits
2540 $$x =~ s/(\d)_(\d)/$1$2/g;
2541 $$x =~ s/(\d)_(\d)/$1$2/g; # do twice for 1_2_3
2543 # some possible inputs:
2544 # 2.1234 # 0.12 # 1 # 1E1 # 2.134E1 # 434E-10 # 1.02009E-2
2545 # .2 # 1_2_3.4_5_6 # 1.4E1_2_3 # 1e3 # +.2
2547 return if $$x =~ /[Ee].*[Ee]/; # more than one E => error
2549 my ($m,$e) = split /[Ee]/,$$x;
2550 $e = '0' if !defined $e || $e eq "";
2551 # sign,value for exponent,mantint,mantfrac
2552 my ($es,$ev,$mis,$miv,$mfv);
2554 if ($e =~ /^([+-]?)0*(\d+)$/) # strip leading zeros
2558 return if $m eq '.' || $m eq '';
2559 my ($mi,$mf,$last) = split /\./,$m;
2560 return if defined $last; # last defined => 1.2.3 or others
2561 $mi = '0' if !defined $mi;
2562 $mi .= '0' if $mi =~ /^[\-\+]?$/;
2563 $mf = '0' if !defined $mf || $mf eq '';
2564 if ($mi =~ /^([+-]?)0*(\d+)$/) # strip leading zeros
2566 $mis = $1||'+'; $miv = $2;
2567 return unless ($mf =~ /^(\d*?)0*$/); # strip trailing zeros
2569 return (\$mis,\$miv,\$mfv,\$es,\$ev);
2572 return; # NaN, not a number
2577 # an object might be asked to return itself as bigint on certain overloaded
2578 # operations, this does exactly this, so that sub classes can simple inherit
2579 # it or override with their own integer conversion routine
2587 # return as hex string, with prefixed 0x
2588 my $x = shift; $x = $class->new($x) if !ref($x);
2590 return $x->bstr() if $x->{sign} !~ /^[+-]$/; # inf, nan etc
2591 return '0x0' if $x->is_zero();
2593 my $es = ''; my $s = '';
2594 $s = $x->{sign} if $x->{sign} eq '-';
2595 if ($CALC->can('_as_hex'))
2597 $es = ${$CALC->_as_hex($x->{value})};
2601 my $x1 = $x->copy()->babs(); my ($xr,$x10000,$h);
2604 $x10000 = Math::BigInt->new (0x10000); $h = 'h4';
2608 $x10000 = Math::BigInt->new (0x1000); $h = 'h3';
2610 while (!$x1->is_zero())
2612 ($x1, $xr) = bdiv($x1,$x10000);
2613 $es .= unpack($h,pack('v',$xr->numify()));
2616 $es =~ s/^[0]+//; # strip leading zeros
2624 # return as binary string, with prefixed 0b
2625 my $x = shift; $x = $class->new($x) if !ref($x);
2627 return $x->bstr() if $x->{sign} !~ /^[+-]$/; # inf, nan etc
2628 return '0b0' if $x->is_zero();
2630 my $es = ''; my $s = '';
2631 $s = $x->{sign} if $x->{sign} eq '-';
2632 if ($CALC->can('_as_bin'))
2634 $es = ${$CALC->_as_bin($x->{value})};
2638 my $x1 = $x->copy()->babs(); my ($xr,$x10000,$b);
2641 $x10000 = Math::BigInt->new (0x10000); $b = 'b16';
2645 $x10000 = Math::BigInt->new (0x1000); $b = 'b12';
2647 while (!$x1->is_zero())
2649 ($x1, $xr) = bdiv($x1,$x10000);
2650 $es .= unpack($b,pack('v',$xr->numify()));
2653 $es =~ s/^[0]+//; # strip leading zeros
2659 ##############################################################################
2660 # internal calculation routines (others are in Math::BigInt::Calc etc)
2664 # (BINT or num_str, BINT or num_str) return BINT
2665 # does modify first argument
2668 my $x = shift; my $ty = shift;
2669 return $x->bnan() if ($x->{sign} eq $nan) || ($ty->{sign} eq $nan);
2670 return $x * $ty / bgcd($x,$ty);
2675 # (BINT or num_str, BINT or num_str) return BINT
2676 # does modify both arguments
2677 # GCD -- Euclids algorithm E, Knuth Vol 2 pg 296
2680 return $x->bnan() if $x->{sign} !~ /^[+-]$/ || $ty->{sign} !~ /^[+-]$/;
2682 while (!$ty->is_zero())
2684 ($x, $ty) = ($ty,bmod($x,$ty));
2689 ###############################################################################
2690 # this method return 0 if the object can be modified, or 1 for not
2691 # We use a fast use constant statement here, to avoid costly calls. Subclasses
2692 # may override it with special code (f.i. Math::BigInt::Constant does so)
2694 sub modify () { 0; }
2701 Math::BigInt - Arbitrary size integer math package
2708 $x = Math::BigInt->new($str); # defaults to 0
2709 $nan = Math::BigInt->bnan(); # create a NotANumber
2710 $zero = Math::BigInt->bzero(); # create a +0
2711 $inf = Math::BigInt->binf(); # create a +inf
2712 $inf = Math::BigInt->binf('-'); # create a -inf
2713 $one = Math::BigInt->bone(); # create a +1
2714 $one = Math::BigInt->bone('-'); # create a -1
2717 $x->is_zero(); # true if arg is +0
2718 $x->is_nan(); # true if arg is NaN
2719 $x->is_one(); # true if arg is +1
2720 $x->is_one('-'); # true if arg is -1
2721 $x->is_odd(); # true if odd, false for even
2722 $x->is_even(); # true if even, false for odd
2723 $x->is_positive(); # true if >= 0
2724 $x->is_negative(); # true if < 0
2725 $x->is_inf(sign); # true if +inf, or -inf (sign is default '+')
2726 $x->is_int(); # true if $x is an integer (not a float)
2728 $x->bcmp($y); # compare numbers (undef,<0,=0,>0)
2729 $x->bacmp($y); # compare absolutely (undef,<0,=0,>0)
2730 $x->sign(); # return the sign, either +,- or NaN
2731 $x->digit($n); # return the nth digit, counting from right
2732 $x->digit(-$n); # return the nth digit, counting from left
2734 # The following all modify their first argument:
2737 $x->bzero(); # set $x to 0
2738 $x->bnan(); # set $x to NaN
2739 $x->bone(); # set $x to +1
2740 $x->bone('-'); # set $x to -1
2741 $x->binf(); # set $x to inf
2742 $x->binf('-'); # set $x to -inf
2744 $x->bneg(); # negation
2745 $x->babs(); # absolute value
2746 $x->bnorm(); # normalize (no-op)
2747 $x->bnot(); # two's complement (bit wise not)
2748 $x->binc(); # increment x by 1
2749 $x->bdec(); # decrement x by 1
2751 $x->badd($y); # addition (add $y to $x)
2752 $x->bsub($y); # subtraction (subtract $y from $x)
2753 $x->bmul($y); # multiplication (multiply $x by $y)
2754 $x->bdiv($y); # divide, set $x to quotient
2755 # return (quo,rem) or quo if scalar
2757 $x->bmod($y); # modulus (x % y)
2758 $x->bmodpow($exp,$mod); # modular exponentation (($num**$exp) % $mod))
2759 $x->bmodinv($mod); # the inverse of $x in the given modulus $mod
2761 $x->bpow($y); # power of arguments (x ** y)
2762 $x->blsft($y); # left shift
2763 $x->brsft($y); # right shift
2764 $x->blsft($y,$n); # left shift, by base $n (like 10)
2765 $x->brsft($y,$n); # right shift, by base $n (like 10)
2767 $x->band($y); # bitwise and
2768 $x->bior($y); # bitwise inclusive or
2769 $x->bxor($y); # bitwise exclusive or
2770 $x->bnot(); # bitwise not (two's complement)
2772 $x->bsqrt(); # calculate square-root
2773 $x->bfac(); # factorial of $x (1*2*3*4*..$x)
2775 $x->round($A,$P,$round_mode); # round to accuracy or precision using mode $r
2776 $x->bround($N); # accuracy: preserve $N digits
2777 $x->bfround($N); # round to $Nth digit, no-op for BigInts
2779 # The following do not modify their arguments in BigInt, but do in BigFloat:
2780 $x->bfloor(); # return integer less or equal than $x
2781 $x->bceil(); # return integer greater or equal than $x
2783 # The following do not modify their arguments:
2785 bgcd(@values); # greatest common divisor (no OO style)
2786 blcm(@values); # lowest common multiplicator (no OO style)
2788 $x->length(); # return number of digits in number
2789 ($x,$f) = $x->length(); # length of number and length of fraction part,
2790 # latter is always 0 digits long for BigInt's
2792 $x->exponent(); # return exponent as BigInt
2793 $x->mantissa(); # return (signed) mantissa as BigInt
2794 $x->parts(); # return (mantissa,exponent) as BigInt
2795 $x->copy(); # make a true copy of $x (unlike $y = $x;)
2796 $x->as_number(); # return as BigInt (in BigInt: same as copy())
2798 # conversation to string
2799 $x->bstr(); # normalized string
2800 $x->bsstr(); # normalized string in scientific notation
2801 $x->as_hex(); # as signed hexadecimal string with prefixed 0x
2802 $x->as_bin(); # as signed binary string with prefixed 0b
2804 Math::BigInt->config(); # return hash containing configuration/version
2806 # precision and accuracy (see section about rounding for more)
2807 $x->precision(); # return P of $x (or global, if P of $x undef)
2808 $x->precision($n); # set P of $x to $n
2809 $x->accuracy(); # return A of $x (or global, if A of $x undef)
2810 $x->accuracy($n); # set A $x to $n
2812 Math::BigInt->precision(); # get/set global P for all BigInt objects
2813 Math::BigInt->accuracy(); # get/set global A for all BigInt objects
2817 All operators (inlcuding basic math operations) are overloaded if you
2818 declare your big integers as
2820 $i = new Math::BigInt '123_456_789_123_456_789';
2822 Operations with overloaded operators preserve the arguments which is
2823 exactly what you expect.
2827 =item Canonical notation
2829 Big integer values are strings of the form C</^[+-]\d+$/> with leading
2832 '-0' canonical value '-0', normalized '0'
2833 ' -123_123_123' canonical value '-123123123'
2834 '1_23_456_7890' canonical value '1234567890'
2838 Input values to these routines may be either Math::BigInt objects or
2839 strings of the form C</^[+-]?[\d]+\.?[\d]*E?[+-]?[\d]*$/>.
2841 You can include one underscore between any two digits. The input string may
2842 have leading and trailing whitespace, which will be ignored. In later
2843 versions, a more strict (no whitespace at all) or more lax (whitespace
2844 allowed everywhere) input checking will also be possible.
2846 This means integer values like 1.01E2 or even 1000E-2 are also accepted.
2847 Non integer values result in NaN.
2849 Math::BigInt::new() defaults to 0, while Math::BigInt::new('') results
2852 bnorm() on a BigInt object is now effectively a no-op, since the numbers
2853 are always stored in normalized form. On a string, it creates a BigInt
2858 Output values are BigInt objects (normalized), except for bstr(), which
2859 returns a string in normalized form.
2860 Some routines (C<is_odd()>, C<is_even()>, C<is_zero()>, C<is_one()>,
2861 C<is_nan()>) return true or false, while others (C<bcmp()>, C<bacmp()>)
2862 return either undef, <0, 0 or >0 and are suited for sort.
2868 Each of the methods below accepts three additional parameters. These arguments
2869 $A, $P and $R are accuracy, precision and round_mode. Please see more in the
2870 section about ACCURACY and ROUNDIND.
2876 print Dumper ( Math::BigInt->config() );
2878 Returns a hash containing the configuration, e.g. the version number, lib
2883 $x->accuracy(5); # local for $x
2884 $class->accuracy(5); # global for all members of $class
2886 Set or get the global or local accuracy, aka how many significant digits the
2887 results have. Please see the section about L<ACCURACY AND PRECISION> for
2890 Value must be greater than zero. Pass an undef value to disable it:
2892 $x->accuracy(undef);
2893 Math::BigInt->accuracy(undef);
2895 Returns the current accuracy. For C<$x->accuracy()> it will return either the
2896 local accuracy, or if not defined, the global. This means the return value
2897 represents the accuracy that will be in effect for $x:
2899 $y = Math::BigInt->new(1234567); # unrounded
2900 print Math::BigInt->accuracy(4),"\n"; # set 4, print 4
2901 $x = Math::BigInt->new(123456); # will be automatically rounded
2902 print "$x $y\n"; # '123500 1234567'
2903 print $x->accuracy(),"\n"; # will be 4
2904 print $y->accuracy(),"\n"; # also 4, since global is 4
2905 print Math::BigInt->accuracy(5),"\n"; # set to 5, print 5
2906 print $x->accuracy(),"\n"; # still 4
2907 print $y->accuracy(),"\n"; # 5, since global is 5
2913 Shifts $x right by $y in base $n. Default is base 2, used are usually 10 and
2914 2, but others work, too.
2916 Right shifting usually amounts to dividing $x by $n ** $y and truncating the
2920 $x = Math::BigInt->new(10);
2921 $x->brsft(1); # same as $x >> 1: 5
2922 $x = Math::BigInt->new(1234);
2923 $x->brsft(2,10); # result 12
2925 There is one exception, and that is base 2 with negative $x:
2928 $x = Math::BigInt->new(-5);
2931 This will print -3, not -2 (as it would if you divide -5 by 2 and truncate the
2936 $x = Math::BigInt->new($str,$A,$P,$R);
2938 Creates a new BigInt object from a string or another BigInt object. The
2939 input is accepted as decimal, hex (with leading '0x') or binary (with leading
2944 $x = Math::BigInt->bnan();
2946 Creates a new BigInt object representing NaN (Not A Number).
2947 If used on an object, it will set it to NaN:
2953 $x = Math::BigInt->bzero();
2955 Creates a new BigInt object representing zero.
2956 If used on an object, it will set it to zero:
2962 $x = Math::BigInt->binf($sign);
2964 Creates a new BigInt object representing infinity. The optional argument is
2965 either '-' or '+', indicating whether you want infinity or minus infinity.
2966 If used on an object, it will set it to infinity:
2973 $x = Math::BigInt->binf($sign);
2975 Creates a new BigInt object representing one. The optional argument is
2976 either '-' or '+', indicating whether you want one or minus one.
2977 If used on an object, it will set it to one:
2982 =head2 is_one()/is_zero()/is_nan()/is_inf()
2985 $x->is_zero(); # true if arg is +0
2986 $x->is_nan(); # true if arg is NaN
2987 $x->is_one(); # true if arg is +1
2988 $x->is_one('-'); # true if arg is -1
2989 $x->is_inf(); # true if +inf
2990 $x->is_inf('-'); # true if -inf (sign is default '+')
2992 These methods all test the BigInt for beeing one specific value and return
2993 true or false depending on the input. These are faster than doing something
2998 =head2 is_positive()/is_negative()
3000 $x->is_positive(); # true if >= 0
3001 $x->is_negative(); # true if < 0
3003 The methods return true if the argument is positive or negative, respectively.
3004 C<NaN> is neither positive nor negative, while C<+inf> counts as positive, and
3005 C<-inf> is negative. A C<zero> is positive.
3007 These methods are only testing the sign, and not the value.
3009 =head2 is_odd()/is_even()/is_int()
3011 $x->is_odd(); # true if odd, false for even
3012 $x->is_even(); # true if even, false for odd
3013 $x->is_int(); # true if $x is an integer
3015 The return true when the argument satisfies the condition. C<NaN>, C<+inf>,
3016 C<-inf> are not integers and are neither odd nor even.
3022 Compares $x with $y and takes the sign into account.
3023 Returns -1, 0, 1 or undef.
3029 Compares $x with $y while ignoring their. Returns -1, 0, 1 or undef.
3035 Return the sign, of $x, meaning either C<+>, C<->, C<-inf>, C<+inf> or NaN.
3039 $x->digit($n); # return the nth digit, counting from right
3045 Negate the number, e.g. change the sign between '+' and '-', or between '+inf'
3046 and '-inf', respectively. Does nothing for NaN or zero.
3052 Set the number to it's absolute value, e.g. change the sign from '-' to '+'
3053 and from '-inf' to '+inf', respectively. Does nothing for NaN or positive
3058 $x->bnorm(); # normalize (no-op)
3062 $x->bnot(); # two's complement (bit wise not)
3066 $x->binc(); # increment x by 1
3070 $x->bdec(); # decrement x by 1
3074 $x->badd($y); # addition (add $y to $x)
3078 $x->bsub($y); # subtraction (subtract $y from $x)
3082 $x->bmul($y); # multiplication (multiply $x by $y)
3086 $x->bdiv($y); # divide, set $x to quotient
3087 # return (quo,rem) or quo if scalar
3091 $x->bmod($y); # modulus (x % y)
3095 $num->bmodinv($mod); # modular inverse
3097 Returns the inverse of C<$num> in the given modulus C<$mod>. 'C<NaN>' is
3098 returned unless C<$num> is relatively prime to C<$mod>, i.e. unless
3099 C<bgcd($num, $mod)==1>.
3103 $num->bmodpow($exp,$mod); # modular exponentation ($num**$exp % $mod)
3105 Returns the value of C<$num> taken to the power C<$exp> in the modulus
3106 C<$mod> using binary exponentation. C<bmodpow> is far superior to
3111 because C<bmodpow> is much faster--it reduces internal variables into
3112 the modulus whenever possible, so it operates on smaller numbers.
3114 C<bmodpow> also supports negative exponents.
3116 bmodpow($num, -1, $mod)
3118 is exactly equivalent to
3124 $x->bpow($y); # power of arguments (x ** y)
3128 $x->blsft($y); # left shift
3129 $x->blsft($y,$n); # left shift, by base $n (like 10)
3133 $x->brsft($y); # right shift
3134 $x->brsft($y,$n); # right shift, by base $n (like 10)
3138 $x->band($y); # bitwise and
3142 $x->bior($y); # bitwise inclusive or
3146 $x->bxor($y); # bitwise exclusive or
3150 $x->bnot(); # bitwise not (two's complement)
3154 $x->bsqrt(); # calculate square-root
3158 $x->bfac(); # factorial of $x (1*2*3*4*..$x)
3162 $x->round($A,$P,$round_mode); # round to accuracy or precision using mode $r
3166 $x->bround($N); # accuracy: preserve $N digits
3170 $x->bfround($N); # round to $Nth digit, no-op for BigInts
3176 Set $x to the integer less or equal than $x. This is a no-op in BigInt, but
3177 does change $x in BigFloat.
3183 Set $x to the integer greater or equal than $x. This is a no-op in BigInt, but
3184 does change $x in BigFloat.
3188 bgcd(@values); # greatest common divisor (no OO style)
3192 blcm(@values); # lowest common multiplicator (no OO style)
3197 ($xl,$fl) = $x->length();
3199 Returns the number of digits in the decimal representation of the number.
3200 In list context, returns the length of the integer and fraction part. For
3201 BigInt's, the length of the fraction part will always be 0.
3207 Return the exponent of $x as BigInt.
3213 Return the signed mantissa of $x as BigInt.
3217 $x->parts(); # return (mantissa,exponent) as BigInt
3221 $x->copy(); # make a true copy of $x (unlike $y = $x;)
3225 $x->as_number(); # return as BigInt (in BigInt: same as copy())
3229 $x->bstr(); # normalized string
3233 $x->bsstr(); # normalized string in scientific notation
3237 $x->as_hex(); # as signed hexadecimal string with prefixed 0x
3241 $x->as_bin(); # as signed binary string with prefixed 0b
3243 =head1 ACCURACY and PRECISION
3245 Since version v1.33, Math::BigInt and Math::BigFloat have full support for
3246 accuracy and precision based rounding, both automatically after every
3247 operation as well as manually.
3249 This section describes the accuracy/precision handling in Math::Big* as it
3250 used to be and as it is now, complete with an explanation of all terms and
3253 Not yet implemented things (but with correct description) are marked with '!',
3254 things that need to be answered are marked with '?'.
3256 In the next paragraph follows a short description of terms used here (because
3257 these may differ from terms used by others people or documentation).
3259 During the rest of this document, the shortcuts A (for accuracy), P (for
3260 precision), F (fallback) and R (rounding mode) will be used.
3264 A fixed number of digits before (positive) or after (negative)
3265 the decimal point. For example, 123.45 has a precision of -2. 0 means an
3266 integer like 123 (or 120). A precision of 2 means two digits to the left
3267 of the decimal point are zero, so 123 with P = 1 becomes 120. Note that
3268 numbers with zeros before the decimal point may have different precisions,
3269 because 1200 can have p = 0, 1 or 2 (depending on what the inital value
3270 was). It could also have p < 0, when the digits after the decimal point
3273 The string output (of floating point numbers) will be padded with zeros:
3275 Initial value P A Result String
3276 ------------------------------------------------------------
3277 1234.01 -3 1000 1000
3280 1234.001 1 1234 1234.0
3282 1234.01 2 1234.01 1234.01
3283 1234.01 5 1234.01 1234.01000
3285 For BigInts, no padding occurs.
3289 Number of significant digits. Leading zeros are not counted. A
3290 number may have an accuracy greater than the non-zero digits
3291 when there are zeros in it or trailing zeros. For example, 123.456 has
3292 A of 6, 10203 has 5, 123.0506 has 7, 123.450000 has 8 and 0.000123 has 3.
3294 The string output (of floating point numbers) will be padded with zeros:
3296 Initial value P A Result String
3297 ------------------------------------------------------------
3299 1234.01 6 1234.01 1234.01
3300 1234.1 8 1234.1 1234.1000
3302 For BigInts, no padding occurs.
3306 When both A and P are undefined, this is used as a fallback accuracy when
3309 =head2 Rounding mode R
3311 When rounding a number, different 'styles' or 'kinds'
3312 of rounding are possible. (Note that random rounding, as in
3313 Math::Round, is not implemented.)
3319 truncation invariably removes all digits following the
3320 rounding place, replacing them with zeros. Thus, 987.65 rounded
3321 to tens (P=1) becomes 980, and rounded to the fourth sigdig
3322 becomes 987.6 (A=4). 123.456 rounded to the second place after the
3323 decimal point (P=-2) becomes 123.46.
3325 All other implemented styles of rounding attempt to round to the
3326 "nearest digit." If the digit D immediately to the right of the
3327 rounding place (skipping the decimal point) is greater than 5, the
3328 number is incremented at the rounding place (possibly causing a
3329 cascade of incrementation): e.g. when rounding to units, 0.9 rounds
3330 to 1, and -19.9 rounds to -20. If D < 5, the number is similarly
3331 truncated at the rounding place: e.g. when rounding to units, 0.4
3332 rounds to 0, and -19.4 rounds to -19.
3334 However the results of other styles of rounding differ if the
3335 digit immediately to the right of the rounding place (skipping the
3336 decimal point) is 5 and if there are no digits, or no digits other
3337 than 0, after that 5. In such cases:
3341 rounds the digit at the rounding place to 0, 2, 4, 6, or 8
3342 if it is not already. E.g., when rounding to the first sigdig, 0.45
3343 becomes 0.4, -0.55 becomes -0.6, but 0.4501 becomes 0.5.
3347 rounds the digit at the rounding place to 1, 3, 5, 7, or 9 if
3348 it is not already. E.g., when rounding to the first sigdig, 0.45
3349 becomes 0.5, -0.55 becomes -0.5, but 0.5501 becomes 0.6.
3353 round to plus infinity, i.e. always round up. E.g., when
3354 rounding to the first sigdig, 0.45 becomes 0.5, -0.55 becomes -0.5,
3355 and 0.4501 also becomes 0.5.
3359 round to minus infinity, i.e. always round down. E.g., when
3360 rounding to the first sigdig, 0.45 becomes 0.4, -0.55 becomes -0.6,
3361 but 0.4501 becomes 0.5.
3365 round to zero, i.e. positive numbers down, negative ones up.
3366 E.g., when rounding to the first sigdig, 0.45 becomes 0.4, -0.55
3367 becomes -0.5, but 0.4501 becomes 0.5.
3371 The handling of A & P in MBI/MBF (the old core code shipped with Perl
3372 versions <= 5.7.2) is like this:
3378 * ffround($p) is able to round to $p number of digits after the decimal
3380 * otherwise P is unused
3382 =item Accuracy (significant digits)
3384 * fround($a) rounds to $a significant digits
3385 * only fdiv() and fsqrt() take A as (optional) paramater
3386 + other operations simply create the same number (fneg etc), or more (fmul)
3388 + rounding/truncating is only done when explicitly calling one of fround
3389 or ffround, and never for BigInt (not implemented)
3390 * fsqrt() simply hands its accuracy argument over to fdiv.
3391 * the documentation and the comment in the code indicate two different ways
3392 on how fdiv() determines the maximum number of digits it should calculate,
3393 and the actual code does yet another thing
3395 max($Math::BigFloat::div_scale,length(dividend)+length(divisor))
3397 result has at most max(scale, length(dividend), length(divisor)) digits
3399 scale = max(scale, length(dividend)-1,length(divisor)-1);
3400 scale += length(divisior) - length(dividend);
3401 So for lx = 3, ly = 9, scale = 10, scale will actually be 16 (10+9-3).
3402 Actually, the 'difference' added to the scale is calculated from the
3403 number of "significant digits" in dividend and divisor, which is derived
3404 by looking at the length of the mantissa. Which is wrong, since it includes
3405 the + sign (oups) and actually gets 2 for '+100' and 4 for '+101'. Oups
3406 again. Thus 124/3 with div_scale=1 will get you '41.3' based on the strange
3407 assumption that 124 has 3 significant digits, while 120/7 will get you
3408 '17', not '17.1' since 120 is thought to have 2 significant digits.
3409 The rounding after the division then uses the remainder and $y to determine
3410 wether it must round up or down.
3411 ? I have no idea which is the right way. That's why I used a slightly more
3412 ? simple scheme and tweaked the few failing testcases to match it.
3416 This is how it works now:
3420 =item Setting/Accessing
3422 * You can set the A global via Math::BigInt->accuracy() or
3423 Math::BigFloat->accuracy() or whatever class you are using.
3424 * You can also set P globally by using Math::SomeClass->precision() likewise.
3425 * Globals are classwide, and not inherited by subclasses.
3426 * to undefine A, use Math::SomeCLass->accuracy(undef);
3427 * to undefine P, use Math::SomeClass->precision(undef);
3428 * Setting Math::SomeClass->accuracy() clears automatically
3429 Math::SomeClass->precision(), and vice versa.
3430 * To be valid, A must be > 0, P can have any value.
3431 * If P is negative, this means round to the P'th place to the right of the
3432 decimal point; positive values mean to the left of the decimal point.
3433 P of 0 means round to integer.
3434 * to find out the current global A, take Math::SomeClass->accuracy()
3435 * to find out the current global P, take Math::SomeClass->precision()
3436 * use $x->accuracy() respective $x->precision() for the local setting of $x.
3437 * Please note that $x->accuracy() respecive $x->precision() fall back to the
3438 defined globals, when $x's A or P is not set.
3440 =item Creating numbers
3442 * When you create a number, you can give it's desired A or P via:
3443 $x = Math::BigInt->new($number,$A,$P);
3444 * Only one of A or P can be defined, otherwise the result is NaN
3445 * If no A or P is give ($x = Math::BigInt->new($number) form), then the
3446 globals (if set) will be used. Thus changing the global defaults later on
3447 will not change the A or P of previously created numbers (i.e., A and P of
3448 $x will be what was in effect when $x was created)
3449 * If given undef for A and P, B<no> rounding will occur, and the globals will
3450 B<not> be used. This is used by subclasses to create numbers without
3451 suffering rounding in the parent. Thus a subclass is able to have it's own
3452 globals enforced upon creation of a number by using
3453 $x = Math::BigInt->new($number,undef,undef):
3455 use Math::Bigint::SomeSubclass;
3458 Math::BigInt->accuracy(2);
3459 Math::BigInt::SomeSubClass->accuracy(3);
3460 $x = Math::BigInt::SomeSubClass->new(1234);
3462 $x is now 1230, and not 1200. A subclass might choose to implement
3463 this otherwise, e.g. falling back to the parent's A and P.
3467 * If A or P are enabled/defined, they are used to round the result of each
3468 operation according to the rules below
3469 * Negative P is ignored in Math::BigInt, since BigInts never have digits
3470 after the decimal point
3471 * Math::BigFloat uses Math::BigInts internally, but setting A or P inside
3472 Math::BigInt as globals should not tamper with the parts of a BigFloat.
3473 Thus a flag is used to mark all Math::BigFloat numbers as 'never round'
3477 * It only makes sense that a number has only one of A or P at a time.
3478 Since you can set/get both A and P, there is a rule that will practically
3479 enforce only A or P to be in effect at a time, even if both are set.
3480 This is called precedence.
3481 * If two objects are involved in an operation, and one of them has A in
3482 effect, and the other P, this results in an error (NaN).
3483 * A takes precendence over P (Hint: A comes before P). If A is defined, it
3484 is used, otherwise P is used. If neither of them is defined, nothing is
3485 used, i.e. the result will have as many digits as it can (with an
3486 exception for fdiv/fsqrt) and will not be rounded.
3487 * There is another setting for fdiv() (and thus for fsqrt()). If neither of
3488 A or P is defined, fdiv() will use a fallback (F) of $div_scale digits.
3489 If either the dividend's or the divisor's mantissa has more digits than
3490 the value of F, the higher value will be used instead of F.
3491 This is to limit the digits (A) of the result (just consider what would
3492 happen with unlimited A and P in the case of 1/3 :-)
3493 * fdiv will calculate (at least) 4 more digits than required (determined by
3494 A, P or F), and, if F is not used, round the result
3495 (this will still fail in the case of a result like 0.12345000000001 with A
3496 or P of 5, but this can not be helped - or can it?)
3497 * Thus you can have the math done by on Math::Big* class in three modes:
3498 + never round (this is the default):
3499 This is done by setting A and P to undef. No math operation
3500 will round the result, with fdiv() and fsqrt() as exceptions to guard
3501 against overflows. You must explicitely call bround(), bfround() or
3502 round() (the latter with parameters).
3503 Note: Once you have rounded a number, the settings will 'stick' on it
3504 and 'infect' all other numbers engaged in math operations with it, since
3505 local settings have the highest precedence. So, to get SaferRound[tm],
3506 use a copy() before rounding like this:
3508 $x = Math::BigFloat->new(12.34);
3509 $y = Math::BigFloat->new(98.76);
3510 $z = $x * $y; # 1218.6984
3511 print $x->copy()->fround(3); # 12.3 (but A is now 3!)
3512 $z = $x * $y; # still 1218.6984, without
3513 # copy would have been 1210!
3515 + round after each op:
3516 After each single operation (except for testing like is_zero()), the
3517 method round() is called and the result is rounded appropriately. By
3518 setting proper values for A and P, you can have all-the-same-A or
3519 all-the-same-P modes. For example, Math::Currency might set A to undef,
3520 and P to -2, globally.
3522 ?Maybe an extra option that forbids local A & P settings would be in order,
3523 ?so that intermediate rounding does not 'poison' further math?
3525 =item Overriding globals
3527 * you will be able to give A, P and R as an argument to all the calculation
3528 routines; the second parameter is A, the third one is P, and the fourth is
3529 R (shift right by one for binary operations like badd). P is used only if
3530 the first parameter (A) is undefined. These three parameters override the
3531 globals in the order detailed as follows, i.e. the first defined value
3533 (local: per object, global: global default, parameter: argument to sub)
3536 + local A (if defined on both of the operands: smaller one is taken)
3537 + local P (if defined on both of the operands: bigger one is taken)
3541 * fsqrt() will hand its arguments to fdiv(), as it used to, only now for two
3542 arguments (A and P) instead of one
3544 =item Local settings
3546 * You can set A and P locally by using $x->accuracy() and $x->precision()
3547 and thus force different A and P for different objects/numbers.
3548 * Setting A or P this way immediately rounds $x to the new value.
3549 * $x->accuracy() clears $x->precision(), and vice versa.
3553 * the rounding routines will use the respective global or local settings.
3554 fround()/bround() is for accuracy rounding, while ffround()/bfround()
3556 * the two rounding functions take as the second parameter one of the
3557 following rounding modes (R):
3558 'even', 'odd', '+inf', '-inf', 'zero', 'trunc'
3559 * you can set and get the global R by using Math::SomeClass->round_mode()
3560 or by setting $Math::SomeClass::round_mode
3561 * after each operation, $result->round() is called, and the result may
3562 eventually be rounded (that is, if A or P were set either locally,
3563 globally or as parameter to the operation)
3564 * to manually round a number, call $x->round($A,$P,$round_mode);
3565 this will round the number by using the appropriate rounding function
3566 and then normalize it.
3567 * rounding modifies the local settings of the number:
3569 $x = Math::BigFloat->new(123.456);
3573 Here 4 takes precedence over 5, so 123.5 is the result and $x->accuracy()
3574 will be 4 from now on.
3576 =item Default values
3585 * The defaults are set up so that the new code gives the same results as
3586 the old code (except in a few cases on fdiv):
3587 + Both A and P are undefined and thus will not be used for rounding
3588 after each operation.
3589 + round() is thus a no-op, unless given extra parameters A and P
3595 The actual numbers are stored as unsigned big integers (with seperate sign).
3596 You should neither care about nor depend on the internal representation; it
3597 might change without notice. Use only method calls like C<< $x->sign(); >>
3598 instead relying on the internal hash keys like in C<< $x->{sign}; >>.
3602 Math with the numbers is done (by default) by a module called
3603 Math::BigInt::Calc. This is equivalent to saying:
3605 use Math::BigInt lib => 'Calc';
3607 You can change this by using:
3609 use Math::BigInt lib => 'BitVect';
3611 The following would first try to find Math::BigInt::Foo, then
3612 Math::BigInt::Bar, and when this also fails, revert to Math::BigInt::Calc:
3614 use Math::BigInt lib => 'Foo,Math::BigInt::Bar';
3616 Calc.pm uses as internal format an array of elements of some decimal base
3617 (usually 1e5 or 1e7) with the least significant digit first, while BitVect.pm
3618 uses a bit vector of base 2, most significant bit first. Other modules might
3619 use even different means of representing the numbers. See the respective
3620 module documentation for further details.
3624 The sign is either '+', '-', 'NaN', '+inf' or '-inf' and stored seperately.
3626 A sign of 'NaN' is used to represent the result when input arguments are not
3627 numbers or as a result of 0/0. '+inf' and '-inf' represent plus respectively
3628 minus infinity. You will get '+inf' when dividing a positive number by 0, and
3629 '-inf' when dividing any negative number by 0.
3631 =head2 mantissa(), exponent() and parts()
3633 C<mantissa()> and C<exponent()> return the said parts of the BigInt such
3636 $m = $x->mantissa();
3637 $e = $x->exponent();
3638 $y = $m * ( 10 ** $e );
3639 print "ok\n" if $x == $y;
3641 C<< ($m,$e) = $x->parts() >> is just a shortcut that gives you both of them
3642 in one go. Both the returned mantissa and exponent have a sign.
3644 Currently, for BigInts C<$e> will be always 0, except for NaN, +inf and -inf,
3645 where it will be NaN; and for $x == 0, where it will be 1
3646 (to be compatible with Math::BigFloat's internal representation of a zero as
3649 C<$m> will always be a copy of the original number. The relation between $e
3650 and $m might change in the future, but will always be equivalent in a
3651 numerical sense, e.g. $m might get minimized.
3657 sub bint { Math::BigInt->new(shift); }
3659 $x = Math::BigInt->bstr("1234") # string "1234"
3660 $x = "$x"; # same as bstr()
3661 $x = Math::BigInt->bneg("1234"); # Bigint "-1234"
3662 $x = Math::BigInt->babs("-12345"); # Bigint "12345"
3663 $x = Math::BigInt->bnorm("-0 00"); # BigInt "0"
3664 $x = bint(1) + bint(2); # BigInt "3"
3665 $x = bint(1) + "2"; # ditto (auto-BigIntify of "2")
3666 $x = bint(1); # BigInt "1"
3667 $x = $x + 5 / 2; # BigInt "3"
3668 $x = $x ** 3; # BigInt "27"
3669 $x *= 2; # BigInt "54"
3670 $x = Math::BigInt->new(0); # BigInt "0"
3672 $x = Math::BigInt->badd(4,5) # BigInt "9"
3673 print $x->bsstr(); # 9e+0
3675 Examples for rounding:
3680 $x = Math::BigFloat->new(123.4567);
3681 $y = Math::BigFloat->new(123.456789);
3682 Math::BigFloat->accuracy(4); # no more A than 4
3684 ok ($x->copy()->fround(),123.4); # even rounding
3685 print $x->copy()->fround(),"\n"; # 123.4
3686 Math::BigFloat->round_mode('odd'); # round to odd
3687 print $x->copy()->fround(),"\n"; # 123.5
3688 Math::BigFloat->accuracy(5); # no more A than 5
3689 Math::BigFloat->round_mode('odd'); # round to odd
3690 print $x->copy()->fround(),"\n"; # 123.46
3691 $y = $x->copy()->fround(4),"\n"; # A = 4: 123.4
3692 print "$y, ",$y->accuracy(),"\n"; # 123.4, 4
3694 Math::BigFloat->accuracy(undef); # A not important now
3695 Math::BigFloat->precision(2); # P important
3696 print $x->copy()->bnorm(),"\n"; # 123.46
3697 print $x->copy()->fround(),"\n"; # 123.46
3699 Examples for converting:
3701 my $x = Math::BigInt->new('0b1'.'01' x 123);
3702 print "bin: ",$x->as_bin()," hex:",$x->as_hex()," dec: ",$x,"\n";
3704 =head1 Autocreating constants
3706 After C<use Math::BigInt ':constant'> all the B<integer> decimal, hexadecimal
3707 and binary constants in the given scope are converted to C<Math::BigInt>.
3708 This conversion happens at compile time.
3712 perl -MMath::BigInt=:constant -e 'print 2**100,"\n"'
3714 prints the integer value of C<2**100>. Note that without conversion of
3715 constants the expression 2**100 will be calculated as perl scalar.
3717 Please note that strings and floating point constants are not affected,
3720 use Math::BigInt qw/:constant/;
3722 $x = 1234567890123456789012345678901234567890
3723 + 123456789123456789;
3724 $y = '1234567890123456789012345678901234567890'
3725 + '123456789123456789';
3727 do not work. You need an explicit Math::BigInt->new() around one of the
3728 operands. You should also quote large constants to protect loss of precision:
3732 $x = Math::BigInt->new('1234567889123456789123456789123456789');
3734 Without the quotes Perl would convert the large number to a floating point
3735 constant at compile time and then hand the result to BigInt, which results in
3736 an truncated result or a NaN.
3738 This also applies to integers that look like floating point constants:
3740 use Math::BigInt ':constant';
3742 print ref(123e2),"\n";
3743 print ref(123.2e2),"\n";
3745 will print nothing but newlines. Use either L<bignum> or L<Math::BigFloat>
3746 to get this to work.
3750 Using the form $x += $y; etc over $x = $x + $y is faster, since a copy of $x
3751 must be made in the second case. For long numbers, the copy can eat up to 20%
3752 of the work (in the case of addition/subtraction, less for
3753 multiplication/division). If $y is very small compared to $x, the form
3754 $x += $y is MUCH faster than $x = $x + $y since making the copy of $x takes
3755 more time then the actual addition.
3757 With a technique called copy-on-write, the cost of copying with overload could
3758 be minimized or even completely avoided. A test implementation of COW did show
3759 performance gains for overloaded math, but introduced a performance loss due
3760 to a constant overhead for all other operatons.
3762 The rewritten version of this module is slower on certain operations, like
3763 new(), bstr() and numify(). The reason are that it does now more work and
3764 handles more cases. The time spent in these operations is usually gained in
3765 the other operations so that programs on the average should get faster. If
3766 they don't, please contect the author.
3768 Some operations may be slower for small numbers, but are significantly faster
3769 for big numbers. Other operations are now constant (O(1), like bneg(), babs()
3770 etc), instead of O(N) and thus nearly always take much less time. These
3771 optimizations were done on purpose.
3773 If you find the Calc module to slow, try to install any of the replacement
3774 modules and see if they help you.
3776 =head2 Alternative math libraries
3778 You can use an alternative library to drive Math::BigInt via:
3780 use Math::BigInt lib => 'Module';
3782 See L<MATH LIBRARY> for more information.
3784 For more benchmark results see L<http://bloodgate.com/perl/benchmarks.html>.
3788 =head1 Subclassing Math::BigInt
3790 The basic design of Math::BigInt allows simple subclasses with very little
3791 work, as long as a few simple rules are followed:
3797 The public API must remain consistent, i.e. if a sub-class is overloading
3798 addition, the sub-class must use the same name, in this case badd(). The
3799 reason for this is that Math::BigInt is optimized to call the object methods
3804 The private object hash keys like C<$x->{sign}> may not be changed, but
3805 additional keys can be added, like C<$x->{_custom}>.
3809 Accessor functions are available for all existing object hash keys and should
3810 be used instead of directly accessing the internal hash keys. The reason for
3811 this is that Math::BigInt itself has a pluggable interface which permits it
3812 to support different storage methods.
3816 More complex sub-classes may have to replicate more of the logic internal of
3817 Math::BigInt if they need to change more basic behaviors. A subclass that
3818 needs to merely change the output only needs to overload C<bstr()>.
3820 All other object methods and overloaded functions can be directly inherited
3821 from the parent class.
3823 At the very minimum, any subclass will need to provide it's own C<new()> and can
3824 store additional hash keys in the object. There are also some package globals
3825 that must be defined, e.g.:
3829 $precision = -2; # round to 2 decimal places
3830 $round_mode = 'even';
3833 Additionally, you might want to provide the following two globals to allow
3834 auto-upgrading and auto-downgrading to work correctly:
3839 This allows Math::BigInt to correctly retrieve package globals from the
3840 subclass, like C<$SubClass::precision>. See t/Math/BigInt/Subclass.pm or
3841 t/Math/BigFloat/SubClass.pm completely functional subclass examples.
3847 in your subclass to automatically inherit the overloading from the parent. If
3848 you like, you can change part of the overloading, look at Math::String for an
3853 When used like this:
3855 use Math::BigInt upgrade => 'Foo::Bar';
3857 certain operations will 'upgrade' their calculation and thus the result to
3858 the class Foo::Bar. Usually this is used in conjunction with Math::BigFloat:
3860 use Math::BigInt upgrade => 'Math::BigFloat';
3862 As a shortcut, you can use the module C<bignum>:
3866 Also good for oneliners:
3868 perl -Mbignum -le 'print 2 ** 255'
3870 This makes it possible to mix arguments of different classes (as in 2.5 + 2)
3871 as well es preserve accuracy (as in sqrt(3)).
3873 Beware: This feature is not fully implemented yet.
3877 The following methods upgrade themselves unconditionally; that is if upgrade
3878 is in effect, they will always hand up their work:
3890 Beware: This list is not complete.
3892 All other methods upgrade themselves only when one (or all) of their
3893 arguments are of the class mentioned in $upgrade (This might change in later
3894 versions to a more sophisticated scheme):
3900 =item Out of Memory!
3902 Under Perl prior to 5.6.0 having an C<use Math::BigInt ':constant';> and
3903 C<eval()> in your code will crash with "Out of memory". This is probably an
3904 overload/exporter bug. You can workaround by not having C<eval()>
3905 and ':constant' at the same time or upgrade your Perl to a newer version.
3907 =item Fails to load Calc on Perl prior 5.6.0
3909 Since eval(' use ...') can not be used in conjunction with ':constant', BigInt
3910 will fall back to eval { require ... } when loading the math lib on Perls
3911 prior to 5.6.0. This simple replaces '::' with '/' and thus might fail on
3912 filesystems using a different seperator.
3918 Some things might not work as you expect them. Below is documented what is
3919 known to be troublesome:
3923 =item stringify, bstr(), bsstr() and 'cmp'
3925 Both stringify and bstr() now drop the leading '+'. The old code would return
3926 '+3', the new returns '3'. This is to be consistent with Perl and to make
3927 cmp (especially with overloading) to work as you expect. It also solves
3928 problems with Test.pm, it's ok() uses 'eq' internally.
3930 Mark said, when asked about to drop the '+' altogether, or make only cmp work:
3932 I agree (with the first alternative), don't add the '+' on positive
3933 numbers. It's not as important anymore with the new internal
3934 form for numbers. It made doing things like abs and neg easier,
3935 but those have to be done differently now anyway.
3937 So, the following examples will now work all as expected:
3940 BEGIN { plan tests => 1 }
3943 my $x = new Math::BigInt 3*3;
3944 my $y = new Math::BigInt 3*3;
3947 print "$x eq 9" if $x eq $y;
3948 print "$x eq 9" if $x eq '9';
3949 print "$x eq 9" if $x eq 3*3;
3951 Additionally, the following still works:
3953 print "$x == 9" if $x == $y;
3954 print "$x == 9" if $x == 9;
3955 print "$x == 9" if $x == 3*3;
3957 There is now a C<bsstr()> method to get the string in scientific notation aka
3958 C<1e+2> instead of C<100>. Be advised that overloaded 'eq' always uses bstr()
3959 for comparisation, but Perl will represent some numbers as 100 and others
3960 as 1e+308. If in doubt, convert both arguments to Math::BigInt before doing eq:
3963 BEGIN { plan tests => 3 }
3966 $x = Math::BigInt->new('1e56'); $y = 1e56;
3967 ok ($x,$y); # will fail
3968 ok ($x->bsstr(),$y); # okay
3969 $y = Math::BigInt->new($y);
3972 Alternatively, simple use <=> for comparisations, that will get it always
3973 right. There is not yet a way to get a number automatically represented as
3974 a string that matches exactly the way Perl represents it.
3978 C<int()> will return (at least for Perl v5.7.1 and up) another BigInt, not a
3981 $x = Math::BigInt->new(123);
3982 $y = int($x); # BigInt 123
3983 $x = Math::BigFloat->new(123.45);
3984 $y = int($x); # BigInt 123
3986 In all Perl versions you can use C<as_number()> for the same effect:
3988 $x = Math::BigFloat->new(123.45);
3989 $y = $x->as_number(); # BigInt 123
3991 This also works for other subclasses, like Math::String.
3993 It is yet unlcear whether overloaded int() should return a scalar or a BigInt.
3997 The following will probably not do what you expect:
3999 $c = Math::BigInt->new(123);
4000 print $c->length(),"\n"; # prints 30
4002 It prints both the number of digits in the number and in the fraction part
4003 since print calls C<length()> in list context. Use something like:
4005 print scalar $c->length(),"\n"; # prints 3
4009 The following will probably not do what you expect:
4011 print $c->bdiv(10000),"\n";
4013 It prints both quotient and remainder since print calls C<bdiv()> in list
4014 context. Also, C<bdiv()> will modify $c, so be carefull. You probably want
4017 print $c / 10000,"\n";
4018 print scalar $c->bdiv(10000),"\n"; # or if you want to modify $c
4022 The quotient is always the greatest integer less than or equal to the
4023 real-valued quotient of the two operands, and the remainder (when it is
4024 nonzero) always has the same sign as the second operand; so, for
4034 As a consequence, the behavior of the operator % agrees with the
4035 behavior of Perl's built-in % operator (as documented in the perlop
4036 manpage), and the equation
4038 $x == ($x / $y) * $y + ($x % $y)
4040 holds true for any $x and $y, which justifies calling the two return
4041 values of bdiv() the quotient and remainder. The only exception to this rule
4042 are when $y == 0 and $x is negative, then the remainder will also be
4043 negative. See below under "infinity handling" for the reasoning behing this.
4045 Perl's 'use integer;' changes the behaviour of % and / for scalars, but will
4046 not change BigInt's way to do things. This is because under 'use integer' Perl
4047 will do what the underlying C thinks is right and this is different for each
4048 system. If you need BigInt's behaving exactly like Perl's 'use integer', bug
4049 the author to implement it ;)
4051 =item infinity handling
4053 Here are some examples that explain the reasons why certain results occur while
4056 The following table shows the result of the division and the remainder, so that
4057 the equation above holds true. Some "ordinary" cases are strewn in to show more
4058 clearly the reasoning:
4060 A / B = C, R so that C * B + R = A
4061 =========================================================
4062 5 / 8 = 0, 5 0 * 8 + 5 = 5
4063 0 / 8 = 0, 0 0 * 8 + 0 = 0
4064 0 / inf = 0, 0 0 * inf + 0 = 0
4065 0 /-inf = 0, 0 0 * -inf + 0 = 0
4066 5 / inf = 0, 5 0 * inf + 5 = 5
4067 5 /-inf = 0, 5 0 * -inf + 5 = 5
4068 -5/ inf = 0, -5 0 * inf + -5 = -5
4069 -5/-inf = 0, -5 0 * -inf + -5 = -5
4070 inf/ 5 = inf, 0 inf * 5 + 0 = inf
4071 -inf/ 5 = -inf, 0 -inf * 5 + 0 = -inf
4072 inf/ -5 = -inf, 0 -inf * -5 + 0 = inf
4073 -inf/ -5 = inf, 0 inf * -5 + 0 = -inf
4074 5/ 5 = 1, 0 1 * 5 + 0 = 5
4075 -5/ -5 = 1, 0 1 * -5 + 0 = -5
4076 inf/ inf = 1, 0 1 * inf + 0 = inf
4077 -inf/-inf = 1, 0 1 * -inf + 0 = -inf
4078 inf/-inf = -1, 0 -1 * -inf + 0 = inf
4079 -inf/ inf = -1, 0 1 * -inf + 0 = -inf
4080 8/ 0 = inf, 8 inf * 0 + 8 = 8
4081 inf/ 0 = inf, inf inf * 0 + inf = inf
4084 These cases below violate the "remainder has the sign of the second of the two
4085 arguments", since they wouldn't match up otherwise.
4087 A / B = C, R so that C * B + R = A
4088 ========================================================
4089 -inf/ 0 = -inf, -inf -inf * 0 + inf = -inf
4090 -8/ 0 = -inf, -8 -inf * 0 + 8 = -8
4092 =item Modifying and =
4096 $x = Math::BigFloat->new(5);
4099 It will not do what you think, e.g. making a copy of $x. Instead it just makes
4100 a second reference to the B<same> object and stores it in $y. Thus anything
4101 that modifies $x (except overloaded operators) will modify $y, and vice versa.
4102 Or in other words, C<=> is only safe if you modify your BigInts only via
4103 overloaded math. As soon as you use a method call it breaks:
4106 print "$x, $y\n"; # prints '10, 10'
4108 If you want a true copy of $x, use:
4112 You can also chain the calls like this, this will make first a copy and then
4115 $y = $x->copy()->bmul(2);
4117 See also the documentation for overload.pm regarding C<=>.
4121 C<bpow()> (and the rounding functions) now modifies the first argument and
4122 returns it, unlike the old code which left it alone and only returned the
4123 result. This is to be consistent with C<badd()> etc. The first three will
4124 modify $x, the last one won't:
4126 print bpow($x,$i),"\n"; # modify $x
4127 print $x->bpow($i),"\n"; # ditto
4128 print $x **= $i,"\n"; # the same
4129 print $x ** $i,"\n"; # leave $x alone
4131 The form C<$x **= $y> is faster than C<$x = $x ** $y;>, though.
4133 =item Overloading -$x
4143 since overload calls C<sub($x,0,1);> instead of C<neg($x)>. The first variant
4144 needs to preserve $x since it does not know that it later will get overwritten.
4145 This makes a copy of $x and takes O(N), but $x->bneg() is O(1).
4147 With Copy-On-Write, this issue would be gone, but C-o-W is not implemented
4148 since it is slower for all other things.
4150 =item Mixing different object types
4152 In Perl you will get a floating point value if you do one of the following:
4158 With overloaded math, only the first two variants will result in a BigFloat:
4163 $mbf = Math::BigFloat->new(5);
4164 $mbi2 = Math::BigInteger->new(5);
4165 $mbi = Math::BigInteger->new(2);
4167 # what actually gets called:
4168 $float = $mbf + $mbi; # $mbf->badd()
4169 $float = $mbf / $mbi; # $mbf->bdiv()
4170 $integer = $mbi + $mbf; # $mbi->badd()
4171 $integer = $mbi2 / $mbi; # $mbi2->bdiv()
4172 $integer = $mbi2 / $mbf; # $mbi2->bdiv()
4174 This is because math with overloaded operators follows the first (dominating)
4175 operand, and the operation of that is called and returns thus the result. So,
4176 Math::BigInt::bdiv() will always return a Math::BigInt, regardless whether
4177 the result should be a Math::BigFloat or the second operant is one.
4179 To get a Math::BigFloat you either need to call the operation manually,
4180 make sure the operands are already of the proper type or casted to that type
4181 via Math::BigFloat->new():
4183 $float = Math::BigFloat->new($mbi2) / $mbi; # = 2.5
4185 Beware of simple "casting" the entire expression, this would only convert
4186 the already computed result:
4188 $float = Math::BigFloat->new($mbi2 / $mbi); # = 2.0 thus wrong!
4190 Beware also of the order of more complicated expressions like:
4192 $integer = ($mbi2 + $mbi) / $mbf; # int / float => int
4193 $integer = $mbi2 / Math::BigFloat->new($mbi); # ditto
4195 If in doubt, break the expression into simpler terms, or cast all operands
4196 to the desired resulting type.
4198 Scalar values are a bit different, since:
4203 will both result in the proper type due to the way the overloaded math works.
4205 This section also applies to other overloaded math packages, like Math::String.
4207 One solution to you problem might be L<autoupgrading|upgrading>.
4211 C<bsqrt()> works only good if the result is a big integer, e.g. the square
4212 root of 144 is 12, but from 12 the square root is 3, regardless of rounding
4215 If you want a better approximation of the square root, then use:
4217 $x = Math::BigFloat->new(12);
4218 Math::BigFloat->precision(0);
4219 Math::BigFloat->round_mode('even');
4220 print $x->copy->bsqrt(),"\n"; # 4
4222 Math::BigFloat->precision(2);
4223 print $x->bsqrt(),"\n"; # 3.46
4224 print $x->bsqrt(3),"\n"; # 3.464
4228 For negative numbers in base see also L<brsft|brsft>.
4234 This program is free software; you may redistribute it and/or modify it under
4235 the same terms as Perl itself.
4239 L<Math::BigFloat> and L<Math::Big> as well as L<Math::BigInt::BitVect>,
4240 L<Math::BigInt::Pari> and L<Math::BigInt::GMP>.
4243 L<http://search.cpan.org/search?mode=module&query=Math%3A%3ABigInt> contains
4244 more documentation including a full version history, testcases, empty
4245 subclass files and benchmarks.
4249 Original code by Mark Biggar, overloaded interface by Ilya Zakharevich.
4250 Completely rewritten by Tels http://bloodgate.com in late 2000, 2001.