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";
23 @ISA = qw( Exporter );
24 @EXPORT_OK = qw( objectify _swap bgcd blcm);
25 use vars qw/$round_mode $accuracy $precision $div_scale $rnd_mode/;
26 use vars qw/$upgrade $downgrade/;
29 # Inside overload, the first arg is always an object. If the original code had
30 # it reversed (like $x = 2 * $y), then the third paramater indicates this
31 # swapping. To make it work, we use a helper routine which not only reswaps the
32 # params, but also makes a new object in this case. See _swap() for details,
33 # especially the cases of operators with different classes.
35 # For overloaded ops with only one argument we simple use $_[0]->copy() to
36 # preserve the argument.
38 # Thus inheritance of overload operators becomes possible and transparent for
39 # our subclasses without the need to repeat the entire overload section there.
42 '=' => sub { $_[0]->copy(); },
44 # '+' and '-' do not use _swap, since it is a triffle slower. If you want to
45 # override _swap (if ever), then override overload of '+' and '-', too!
46 # for sub it is a bit tricky to keep b: b-a => -a+b
47 '-' => sub { my $c = $_[0]->copy; $_[2] ?
48 $c->bneg()->badd($_[1]) :
50 '+' => sub { $_[0]->copy()->badd($_[1]); },
52 # some shortcuts for speed (assumes that reversed order of arguments is routed
53 # to normal '+' and we thus can always modify first arg. If this is changed,
54 # this breaks and must be adjusted.)
55 '+=' => sub { $_[0]->badd($_[1]); },
56 '-=' => sub { $_[0]->bsub($_[1]); },
57 '*=' => sub { $_[0]->bmul($_[1]); },
58 '/=' => sub { scalar $_[0]->bdiv($_[1]); },
59 '%=' => sub { $_[0]->bmod($_[1]); },
60 '^=' => sub { $_[0]->bxor($_[1]); },
61 '&=' => sub { $_[0]->band($_[1]); },
62 '|=' => sub { $_[0]->bior($_[1]); },
63 '**=' => sub { $_[0]->bpow($_[1]); },
65 # not supported by Perl yet
66 '..' => \&_pointpoint,
68 '<=>' => sub { $_[2] ?
69 ref($_[0])->bcmp($_[1],$_[0]) :
70 ref($_[0])->bcmp($_[0],$_[1])},
73 "$_[1]" cmp $_[0]->bstr() :
74 $_[0]->bstr() cmp "$_[1]" },
76 'log' => sub { $_[0]->copy()->blog(); },
77 'int' => sub { $_[0]->copy(); },
78 'neg' => sub { $_[0]->copy()->bneg(); },
79 'abs' => sub { $_[0]->copy()->babs(); },
80 'sqrt' => sub { $_[0]->copy()->bsqrt(); },
81 '~' => sub { $_[0]->copy()->bnot(); },
83 '*' => sub { my @a = ref($_[0])->_swap(@_); $a[0]->bmul($a[1]); },
84 '/' => sub { my @a = ref($_[0])->_swap(@_);scalar $a[0]->bdiv($a[1]);},
85 '%' => sub { my @a = ref($_[0])->_swap(@_); $a[0]->bmod($a[1]); },
86 '**' => sub { my @a = ref($_[0])->_swap(@_); $a[0]->bpow($a[1]); },
87 '<<' => sub { my @a = ref($_[0])->_swap(@_); $a[0]->blsft($a[1]); },
88 '>>' => sub { my @a = ref($_[0])->_swap(@_); $a[0]->brsft($a[1]); },
90 '&' => sub { my @a = ref($_[0])->_swap(@_); $a[0]->band($a[1]); },
91 '|' => sub { my @a = ref($_[0])->_swap(@_); $a[0]->bior($a[1]); },
92 '^' => sub { my @a = ref($_[0])->_swap(@_); $a[0]->bxor($a[1]); },
94 # can modify arg of ++ and --, so avoid a new-copy for speed, but don't
95 # use $_[0]->__one(), it modifies $_[0] to be 1!
96 '++' => sub { $_[0]->binc() },
97 '--' => sub { $_[0]->bdec() },
99 # if overloaded, O(1) instead of O(N) and twice as fast for small numbers
101 # this kludge is needed for perl prior 5.6.0 since returning 0 here fails :-/
102 # v5.6.1 dumps on that: return !$_[0]->is_zero() || undef; :-(
103 my $t = !$_[0]->is_zero();
108 # the original qw() does not work with the TIESCALAR below, why?
109 # Order of arguments unsignificant
110 '""' => sub { $_[0]->bstr(); },
111 '0+' => sub { $_[0]->numify(); }
114 ##############################################################################
115 # global constants, flags and accessory
117 use constant MB_NEVER_ROUND => 0x0001;
119 my $NaNOK=1; # are NaNs ok?
120 my $nan = 'NaN'; # constants for easier life
122 my $CALC = 'Math::BigInt::Calc'; # module to do low level math
123 my $IMPORT = 0; # did import() yet?
125 $round_mode = 'even'; # one of 'even', 'odd', '+inf', '-inf', 'zero' or 'trunc'
130 $upgrade = undef; # default is no upgrade
131 $downgrade = undef; # default is no downgrade
133 ##############################################################################
134 # the old code had $rnd_mode, so we need to support it, too
137 sub TIESCALAR { my ($class) = @_; bless \$round_mode, $class; }
138 sub FETCH { return $round_mode; }
139 sub STORE { $rnd_mode = $_[0]->round_mode($_[1]); }
141 BEGIN { tie $rnd_mode, 'Math::BigInt'; }
143 ##############################################################################
148 # make Class->round_mode() work
150 my $class = ref($self) || $self || __PACKAGE__;
154 die "Unknown round mode $m"
155 if $m !~ /^(even|odd|\+inf|\-inf|zero|trunc)$/;
156 return ${"${class}::round_mode"} = $m;
158 return ${"${class}::round_mode"};
164 # make Class->upgrade() work
166 my $class = ref($self) || $self || __PACKAGE__;
167 # need to set new value?
171 return ${"${class}::upgrade"} = $u;
173 return ${"${class}::upgrade"};
179 # make Class->downgrade() work
181 my $class = ref($self) || $self || __PACKAGE__;
182 # need to set new value?
186 return ${"${class}::downgrade"} = $u;
188 return ${"${class}::downgrade"};
194 # make Class->round_mode() work
196 my $class = ref($self) || $self || __PACKAGE__;
199 die ('div_scale must be greater than zero') if $_[0] < 0;
200 ${"${class}::div_scale"} = shift;
202 return ${"${class}::div_scale"};
207 # $x->accuracy($a); ref($x) $a
208 # $x->accuracy(); ref($x)
209 # Class->accuracy(); class
210 # Class->accuracy($a); class $a
213 my $class = ref($x) || $x || __PACKAGE__;
216 # need to set new value?
220 die ('accuracy must not be zero') if defined $a && $a == 0;
223 # $object->accuracy() or fallback to global
224 $x->bround($a) if defined $a;
225 $x->{_a} = $a; # set/overwrite, even if not rounded
226 $x->{_p} = undef; # clear P
231 ${"${class}::accuracy"} = $a;
232 ${"${class}::precision"} = undef; # clear P
234 return $a; # shortcut
239 # $object->accuracy() or fallback to global
240 return $x->{_a} || ${"${class}::accuracy"};
242 return ${"${class}::accuracy"};
247 # $x->precision($p); ref($x) $p
248 # $x->precision(); ref($x)
249 # Class->precision(); class
250 # Class->precision($p); class $p
253 my $class = ref($x) || $x || __PACKAGE__;
256 # need to set new value?
262 # $object->precision() or fallback to global
263 $x->bfround($p) if defined $p;
264 $x->{_p} = $p; # set/overwrite, even if not rounded
265 $x->{_a} = undef; # clear A
270 ${"${class}::precision"} = $p;
271 ${"${class}::accuracy"} = undef; # clear A
273 return $p; # shortcut
278 # $object->precision() or fallback to global
279 return $x->{_p} || ${"${class}::precision"};
281 return ${"${class}::precision"};
286 # return (later set?) configuration data as hash ref
287 my $class = shift || 'Math::BigInt';
293 lib_version => ${"${lib}::VERSION"},
297 qw/upgrade downgrade precision accuracy round_mode VERSION div_scale/)
299 $cfg->{lc($_)} = ${"${class}::$_"};
306 # select accuracy parameter based on precedence,
307 # used by bround() and bfround(), may return undef for scale (means no op)
308 my ($x,$s,$m,$scale,$mode) = @_;
309 $scale = $x->{_a} if !defined $scale;
310 $scale = $s if (!defined $scale);
311 $mode = $m if !defined $mode;
312 return ($scale,$mode);
317 # select precision parameter based on precedence,
318 # used by bround() and bfround(), may return undef for scale (means no op)
319 my ($x,$s,$m,$scale,$mode) = @_;
320 $scale = $x->{_p} if !defined $scale;
321 $scale = $s if (!defined $scale);
322 $mode = $m if !defined $mode;
323 return ($scale,$mode);
326 ##############################################################################
334 # if two arguments, the first one is the class to "swallow" subclasses
342 return unless ref($x); # only for objects
344 my $self = {}; bless $self,$c;
346 foreach my $k (keys %$x)
350 $self->{value} = $CALC->_copy($x->{value}); next;
352 if (!($r = ref($x->{$k})))
354 $self->{$k} = $x->{$k}; next;
358 $self->{$k} = \${$x->{$k}};
360 elsif ($r eq 'ARRAY')
362 $self->{$k} = [ @{$x->{$k}} ];
366 # only one level deep!
367 foreach my $h (keys %{$x->{$k}})
369 $self->{$k}->{$h} = $x->{$k}->{$h};
375 if ($xk->can('copy'))
377 $self->{$k} = $xk->copy();
381 $self->{$k} = $xk->new($xk);
390 # create a new BigInt object from a string or another BigInt object.
391 # see hash keys documented at top
393 # the argument could be an object, so avoid ||, && etc on it, this would
394 # cause costly overloaded code to be called. The only allowed ops are
397 my ($class,$wanted,$a,$p,$r) = @_;
399 # avoid numify-calls by not using || on $wanted!
400 return $class->bzero($a,$p) if !defined $wanted; # default to 0
401 return $class->copy($wanted,$a,$p,$r)
402 if ref($wanted) && $wanted->isa($class); # MBI or subclass
404 $class->import() if $IMPORT == 0; # make require work
406 my $self = bless {}, $class;
408 # shortcut for "normal" numbers
409 if ((!ref $wanted) && ($wanted =~ /^([+-]?)[1-9][0-9]*$/))
411 $self->{sign} = $1 || '+';
413 if ($wanted =~ /^[+-]/)
415 # remove sign without touching wanted
416 my $t = $wanted; $t =~ s/^[+-]//; $ref = \$t;
418 $self->{value} = $CALC->_new($ref);
420 if ( (defined $a) || (defined $p)
421 || (defined ${"${class}::precision"})
422 || (defined ${"${class}::accuracy"})
425 $self->round($a,$p,$r) unless (@_ == 4 && !defined $a && !defined $p);
430 # handle '+inf', '-inf' first
431 if ($wanted =~ /^[+-]?inf$/)
433 $self->{value} = $CALC->_zero();
434 $self->{sign} = $wanted; $self->{sign} = '+inf' if $self->{sign} eq 'inf';
437 # split str in m mantissa, e exponent, i integer, f fraction, v value, s sign
438 my ($mis,$miv,$mfv,$es,$ev) = _split(\$wanted);
441 die "$wanted is not a number initialized to $class" if !$NaNOK;
443 $self->{value} = $CALC->_zero();
444 $self->{sign} = $nan;
449 # _from_hex or _from_bin
450 $self->{value} = $mis->{value};
451 $self->{sign} = $mis->{sign};
452 return $self; # throw away $mis
454 # make integer from mantissa by adjusting exp, then convert to bigint
455 $self->{sign} = $$mis; # store sign
456 $self->{value} = $CALC->_zero(); # for all the NaN cases
457 my $e = int("$$es$$ev"); # exponent (avoid recursion)
460 my $diff = $e - CORE::length($$mfv);
461 if ($diff < 0) # Not integer
464 return $upgrade->new($wanted,$a,$p,$r) if defined $upgrade;
465 $self->{sign} = $nan;
469 # adjust fraction and add it to value
470 # print "diff > 0 $$miv\n";
471 $$miv = $$miv . ($$mfv . '0' x $diff);
476 if ($$mfv ne '') # e <= 0
478 # fraction and negative/zero E => NOI
479 #print "NOI 2 \$\$mfv '$$mfv'\n";
480 return $upgrade->new($wanted,$a,$p,$r) if defined $upgrade;
481 $self->{sign} = $nan;
485 # xE-y, and empty mfv
488 if ($$miv !~ s/0{$e}$//) # can strip so many zero's?
491 return $upgrade->new($wanted,$a,$p,$r) if defined $upgrade;
492 $self->{sign} = $nan;
496 $self->{sign} = '+' if $$miv eq '0'; # normalize -0 => +0
497 $self->{value} = $CALC->_new($miv) if $self->{sign} =~ /^[+-]$/;
498 # if any of the globals is set, use them to round and store them inside $self
499 # do not round for new($x,undef,undef) since that is used by MBF to signal
501 $self->round($a,$p,$r) unless @_ == 4 && !defined $a && !defined $p;
507 # create a bigint 'NaN', if given a BigInt, set it to 'NaN'
509 $self = $class if !defined $self;
512 my $c = $self; $self = {}; bless $self, $c;
514 $self->import() if $IMPORT == 0; # make require work
515 return if $self->modify('bnan');
517 if ($self->can('_bnan'))
519 # use subclass to initialize
524 # otherwise do our own thing
525 $self->{value} = $CALC->_zero();
527 $self->{sign} = $nan;
528 delete $self->{_a}; delete $self->{_p}; # rounding NaN is silly
534 # create a bigint '+-inf', if given a BigInt, set it to '+-inf'
535 # the sign is either '+', or if given, used from there
537 my $sign = shift; $sign = '+' if !defined $sign || $sign !~ /^-(inf)?$/;
538 $self = $class if !defined $self;
541 my $c = $self; $self = {}; bless $self, $c;
543 $self->import() if $IMPORT == 0; # make require work
544 return if $self->modify('binf');
546 if ($self->can('_binf'))
548 # use subclass to initialize
553 # otherwise do our own thing
554 $self->{value} = $CALC->_zero();
556 $sign = $sign . 'inf' if $sign !~ /inf$/; # - => -inf
557 $self->{sign} = $sign;
558 ($self->{_a},$self->{_p}) = @_; # take over requested rounding
564 # create a bigint '+0', if given a BigInt, set it to 0
566 $self = $class if !defined $self;
570 my $c = $self; $self = {}; bless $self, $c;
572 $self->import() if $IMPORT == 0; # make require work
573 return if $self->modify('bzero');
575 if ($self->can('_bzero'))
577 # use subclass to initialize
582 # otherwise do our own thing
583 $self->{value} = $CALC->_zero();
589 if (defined $self->{_a} && defined $_[0] && $_[0] > $self->{_a});
591 if (defined $self->{_p} && defined $_[1] && $_[1] < $self->{_p});
598 # create a bigint '+1' (or -1 if given sign '-'),
599 # if given a BigInt, set it to +1 or -1, respecively
601 my $sign = shift; $sign = '+' if !defined $sign || $sign ne '-';
602 $self = $class if !defined $self;
606 my $c = $self; $self = {}; bless $self, $c;
608 $self->import() if $IMPORT == 0; # make require work
609 return if $self->modify('bone');
611 if ($self->can('_bone'))
613 # use subclass to initialize
618 # otherwise do our own thing
619 $self->{value} = $CALC->_one();
621 $self->{sign} = $sign;
625 if (defined $self->{_a} && defined $_[0] && $_[0] > $self->{_a});
627 if (defined $self->{_p} && defined $_[1] && $_[1] < $self->{_p});
632 ##############################################################################
633 # string conversation
637 # (ref to BFLOAT or num_str ) return num_str
638 # Convert number from internal format to scientific string format.
639 # internal format is always normalized (no leading zeros, "-0E0" => "+0E0")
640 my $x = shift; $class = ref($x) || $x; $x = $class->new(shift) if !ref($x);
641 # my ($self,$x) = ref($_[0]) ? (ref($_[0]),$_[0]) : objectify(1,@_);
643 if ($x->{sign} !~ /^[+-]$/)
645 return $x->{sign} unless $x->{sign} eq '+inf'; # -inf, NaN
648 my ($m,$e) = $x->parts();
649 # e can only be positive
651 # MBF: my $s = $e->{sign}; $s = '' if $s eq '-'; my $sep = 'e'.$s;
652 return $m->bstr().$sign.$e->bstr();
657 # make a string from bigint object
658 my $x = shift; $class = ref($x) || $x; $x = $class->new(shift) if !ref($x);
659 # my ($self,$x) = ref($_[0]) ? (ref($_[0]),$_[0]) : objectify(1,@_);
661 if ($x->{sign} !~ /^[+-]$/)
663 return $x->{sign} unless $x->{sign} eq '+inf'; # -inf, NaN
666 my $es = ''; $es = $x->{sign} if $x->{sign} eq '-';
667 return $es.${$CALC->_str($x->{value})};
672 # Make a "normal" scalar from a BigInt object
673 my $x = shift; $x = $class->new($x) unless ref $x;
674 return $x->{sign} if $x->{sign} !~ /^[+-]$/;
675 my $num = $CALC->_num($x->{value});
676 return -$num if $x->{sign} eq '-';
680 ##############################################################################
681 # public stuff (usually prefixed with "b")
685 # return the sign of the number: +/-/-inf/+inf/NaN
686 my ($self,$x) = ref($_[0]) ? (ref($_[0]),$_[0]) : objectify(1,@_);
691 sub _find_round_parameters
693 # After any operation or when calling round(), the result is rounded by
694 # regarding the A & P from arguments, local parameters, or globals.
696 # This procedure finds the round parameters, but it is for speed reasons
697 # duplicated in round. Otherwise, it is tested by the testsuite and used
700 my ($self,$a,$p,$r,@args) = @_;
701 # $a accuracy, if given by caller
702 # $p precision, if given by caller
703 # $r round_mode, if given by caller
704 # @args all 'other' arguments (0 for unary, 1 for binary ops)
706 # leave bigfloat parts alone
707 return ($self) if exists $self->{_f} && $self->{_f} & MB_NEVER_ROUND != 0;
709 my $c = ref($self); # find out class of argument(s)
712 # now pick $a or $p, but only if we have got "arguments"
715 foreach ($self,@args)
717 # take the defined one, or if both defined, the one that is smaller
718 $a = $_->{_a} if (defined $_->{_a}) && (!defined $a || $_->{_a} < $a);
723 # even if $a is defined, take $p, to signal error for both defined
724 foreach ($self,@args)
726 # take the defined one, or if both defined, the one that is bigger
728 $p = $_->{_p} if (defined $_->{_p}) && (!defined $p || $_->{_p} > $p);
731 # if still none defined, use globals (#2)
732 $a = ${"$c\::accuracy"} unless defined $a;
733 $p = ${"$c\::precision"} unless defined $p;
736 return ($self) unless defined $a || defined $p; # early out
738 # set A and set P is an fatal error
739 return ($self->bnan()) if defined $a && defined $p;
741 $r = ${"$c\::round_mode"} unless defined $r;
742 die "Unknown round mode '$r'" if $r !~ /^(even|odd|\+inf|\-inf|zero|trunc)$/;
744 return ($self,$a,$p,$r);
749 # Round $self according to given parameters, or given second argument's
750 # parameters or global defaults
752 # for speed reasons, _find_round_parameters is embeded here:
754 my ($self,$a,$p,$r,@args) = @_;
755 # $a accuracy, if given by caller
756 # $p precision, if given by caller
757 # $r round_mode, if given by caller
758 # @args all 'other' arguments (0 for unary, 1 for binary ops)
760 # leave bigfloat parts alone
761 return ($self) if exists $self->{_f} && $self->{_f} & MB_NEVER_ROUND != 0;
763 my $c = ref($self); # find out class of argument(s)
766 # now pick $a or $p, but only if we have got "arguments"
769 foreach ($self,@args)
771 # take the defined one, or if both defined, the one that is smaller
772 $a = $_->{_a} if (defined $_->{_a}) && (!defined $a || $_->{_a} < $a);
777 # even if $a is defined, take $p, to signal error for both defined
778 foreach ($self,@args)
780 # take the defined one, or if both defined, the one that is bigger
782 $p = $_->{_p} if (defined $_->{_p}) && (!defined $p || $_->{_p} > $p);
785 # if still none defined, use globals (#2)
786 $a = ${"$c\::accuracy"} unless defined $a;
787 $p = ${"$c\::precision"} unless defined $p;
790 return $self unless defined $a || defined $p; # early out
792 # set A and set P is an fatal error
793 return $self->bnan() if defined $a && defined $p;
795 $r = ${"$c\::round_mode"} unless defined $r;
796 die "Unknown round mode '$r'" if $r !~ /^(even|odd|\+inf|\-inf|zero|trunc)$/;
798 # now round, by calling either fround or ffround:
801 $self->bround($a,$r) if !defined $self->{_a} || $self->{_a} >= $a;
803 else # both can't be undefined due to early out
805 $self->bfround($p,$r) if !defined $self->{_p} || $self->{_p} <= $p;
807 $self->bnorm(); # after round, normalize
812 # (numstr or BINT) return BINT
813 # Normalize number -- no-op here
814 my ($self,$x) = ref($_[0]) ? (ref($_[0]),$_[0]) : objectify(1,@_);
820 # (BINT or num_str) return BINT
821 # make number absolute, or return absolute BINT from string
822 my ($self,$x) = ref($_[0]) ? (ref($_[0]),$_[0]) : objectify(1,@_);
824 return $x if $x->modify('babs');
825 # post-normalized abs for internal use (does nothing for NaN)
826 $x->{sign} =~ s/^-/+/;
832 # (BINT or num_str) return BINT
833 # negate number or make a negated number from string
834 my ($self,$x) = ref($_[0]) ? (ref($_[0]),$_[0]) : objectify(1,@_);
836 return $x if $x->modify('bneg');
838 # for +0 dont negate (to have always normalized)
839 $x->{sign} =~ tr/+-/-+/ if !$x->is_zero(); # does nothing for NaN
845 # Compares 2 values. Returns one of undef, <0, =0, >0. (suitable for sort)
846 # (BINT or num_str, BINT or num_str) return cond_code
847 my ($self,$x,$y) = objectify(2,@_);
849 if (($x->{sign} !~ /^[+-]$/) || ($y->{sign} !~ /^[+-]$/))
851 # handle +-inf and NaN
852 return undef if (($x->{sign} eq $nan) || ($y->{sign} eq $nan));
853 return 0 if $x->{sign} eq $y->{sign} && $x->{sign} =~ /^[+-]inf$/;
854 return +1 if $x->{sign} eq '+inf';
855 return -1 if $x->{sign} eq '-inf';
856 return -1 if $y->{sign} eq '+inf';
859 # check sign for speed first
860 return 1 if $x->{sign} eq '+' && $y->{sign} eq '-'; # does also 0 <=> -y
861 return -1 if $x->{sign} eq '-' && $y->{sign} eq '+'; # does also -x <=> 0
864 my $xz = $x->is_zero();
865 my $yz = $y->is_zero();
866 return 0 if $xz && $yz; # 0 <=> 0
867 return -1 if $xz && $y->{sign} eq '+'; # 0 <=> +y
868 return 1 if $yz && $x->{sign} eq '+'; # +x <=> 0
870 # post-normalized compare for internal use (honors signs)
871 if ($x->{sign} eq '+')
874 return $CALC->_acmp($x->{value},$y->{value});
878 $CALC->_acmp($y->{value},$x->{value}); # swaped (lib does only 0,1,-1)
883 # Compares 2 values, ignoring their signs.
884 # Returns one of undef, <0, =0, >0. (suitable for sort)
885 # (BINT, BINT) return cond_code
886 my ($self,$x,$y) = objectify(2,@_);
888 if (($x->{sign} !~ /^[+-]$/) || ($y->{sign} !~ /^[+-]$/))
890 # handle +-inf and NaN
891 return undef if (($x->{sign} eq $nan) || ($y->{sign} eq $nan));
892 return 0 if $x->{sign} =~ /^[+-]inf$/ && $y->{sign} =~ /^[+-]inf$/;
893 return +1; # inf is always bigger
895 $CALC->_acmp($x->{value},$y->{value}); # lib does only 0,1,-1
900 # add second arg (BINT or string) to first (BINT) (modifies first)
901 # return result as BINT
902 my ($self,$x,$y,@r) = objectify(2,@_);
904 return $x if $x->modify('badd');
905 return $upgrade->badd($x,$y,@r) if defined $upgrade &&
906 ((!$x->isa($self)) || (!$y->isa($self)));
908 $r[3] = $y; # no push!
909 # inf and NaN handling
910 if (($x->{sign} !~ /^[+-]$/) || ($y->{sign} !~ /^[+-]$/))
913 return $x->bnan() if (($x->{sign} eq $nan) || ($y->{sign} eq $nan));
915 if (($x->{sign} =~ /^[+-]inf$/) && ($y->{sign} =~ /^[+-]inf$/))
917 # +inf++inf or -inf+-inf => same, rest is NaN
918 return $x if $x->{sign} eq $y->{sign};
921 # +-inf + something => +inf
922 # something +-inf => +-inf
923 $x->{sign} = $y->{sign}, return $x if $y->{sign} =~ /^[+-]inf$/;
927 my ($sx, $sy) = ( $x->{sign}, $y->{sign} ); # get signs
931 $x->{value} = $CALC->_add($x->{value},$y->{value}); # same sign, abs add
936 my $a = $CALC->_acmp ($y->{value},$x->{value}); # absolute compare
939 #print "swapped sub (a=$a)\n";
940 $x->{value} = $CALC->_sub($y->{value},$x->{value},1); # abs sub w/ swap
945 # speedup, if equal, set result to 0
946 #print "equal sub, result = 0\n";
947 $x->{value} = $CALC->_zero();
952 #print "unswapped sub (a=$a)\n";
953 $x->{value} = $CALC->_sub($x->{value}, $y->{value}); # abs sub
962 # (BINT or num_str, BINT or num_str) return num_str
963 # subtract second arg from first, modify first
964 my ($self,$x,$y,@r) = objectify(2,@_);
966 return $x if $x->modify('bsub');
968 # upgrade done by badd():
969 # return $upgrade->badd($x,$y,@r) if defined $upgrade &&
970 # ((!$x->isa($self)) || (!$y->isa($self)));
974 return $x->round(@r);
977 $y->{sign} =~ tr/+\-/-+/; # does nothing for NaN
978 $x->badd($y,@r); # badd does not leave internal zeros
979 $y->{sign} =~ tr/+\-/-+/; # refix $y (does nothing for NaN)
980 $x; # already rounded by badd() or no round necc.
985 # increment arg by one
986 my ($self,$x,$a,$p,$r) = ref($_[0]) ? (ref($_[0]),@_) : objectify(1,@_);
987 return $x if $x->modify('binc');
989 if ($x->{sign} eq '+')
991 $x->{value} = $CALC->_inc($x->{value});
992 return $x->round($a,$p,$r);
994 elsif ($x->{sign} eq '-')
996 $x->{value} = $CALC->_dec($x->{value});
997 $x->{sign} = '+' if $CALC->_is_zero($x->{value}); # -1 +1 => -0 => +0
998 return $x->round($a,$p,$r);
1000 # inf, nan handling etc
1001 $x->badd($self->__one(),$a,$p,$r); # badd does round
1006 # decrement arg by one
1007 my ($self,$x,$a,$p,$r) = ref($_[0]) ? (ref($_[0]),@_) : objectify(1,@_);
1008 return $x if $x->modify('bdec');
1010 my $zero = $CALC->_is_zero($x->{value}) && $x->{sign} eq '+';
1012 if (($x->{sign} eq '-') || $zero)
1014 $x->{value} = $CALC->_inc($x->{value});
1015 $x->{sign} = '-' if $zero; # 0 => 1 => -1
1016 $x->{sign} = '+' if $CALC->_is_zero($x->{value}); # -1 +1 => -0 => +0
1017 return $x->round($a,$p,$r);
1020 elsif ($x->{sign} eq '+')
1022 $x->{value} = $CALC->_dec($x->{value});
1023 return $x->round($a,$p,$r);
1025 # inf, nan handling etc
1026 $x->badd($self->__one('-'),$a,$p,$r); # badd does round
1031 # not implemented yet
1032 my ($self,$x,$base,$a,$p,$r) = ref($_[0]) ? (ref($_[0]),@_) : objectify(1,@_);
1034 return $upgrade->blog($x,$base,$a,$p,$r) if defined $upgrade;
1041 # (BINT or num_str, BINT or num_str) return BINT
1042 # does not modify arguments, but returns new object
1043 # Lowest Common Multiplicator
1045 my $y = shift; my ($x);
1052 $x = $class->new($y);
1054 while (@_) { $x = __lcm($x,shift); }
1060 # (BINT or num_str, BINT or num_str) return BINT
1061 # does not modify arguments, but returns new object
1062 # GCD -- Euclids algorithm, variant C (Knuth Vol 3, pg 341 ff)
1065 $y = __PACKAGE__->new($y) if !ref($y);
1067 my $x = $y->copy(); # keep arguments
1068 if ($CALC->can('_gcd'))
1072 $y = shift; $y = $self->new($y) if !ref($y);
1073 next if $y->is_zero();
1074 return $x->bnan() if $y->{sign} !~ /^[+-]$/; # y NaN?
1075 $x->{value} = $CALC->_gcd($x->{value},$y->{value}); last if $x->is_one();
1082 $y = shift; $y = $self->new($y) if !ref($y);
1083 $x = __gcd($x,$y->copy()); last if $x->is_one(); # _gcd handles NaN
1091 # (num_str or BINT) return BINT
1092 # represent ~x as twos-complement number
1093 # we don't need $self, so undef instead of ref($_[0]) make it slightly faster
1094 my ($self,$x,$a,$p,$r) = ref($_[0]) ? (undef,@_) : objectify(1,@_);
1096 return $x if $x->modify('bnot');
1097 $x->bneg()->bdec(); # bdec already does round
1100 # is_foo test routines
1104 # return true if arg (BINT or num_str) is zero (array '+', '0')
1105 # we don't need $self, so undef instead of ref($_[0]) make it slightly faster
1106 my ($self,$x) = ref($_[0]) ? (undef,$_[0]) : objectify(1,@_);
1108 return 0 if $x->{sign} !~ /^\+$/; # -, NaN & +-inf aren't
1109 $CALC->_is_zero($x->{value});
1114 # return true if arg (BINT or num_str) is NaN
1115 my ($self,$x) = ref($_[0]) ? (ref($_[0]),$_[0]) : objectify(1,@_);
1117 return 1 if $x->{sign} eq $nan;
1123 # return true if arg (BINT or num_str) is +-inf
1124 my ($self,$x,$sign) = ref($_[0]) ? (ref($_[0]),@_) : objectify(1,@_);
1126 $sign = '' if !defined $sign;
1127 return 1 if $sign eq $x->{sign}; # match ("+inf" eq "+inf")
1128 return 0 if $sign !~ /^([+-]|)$/;
1132 return 1 if ($x->{sign} =~ /^[+-]inf$/);
1135 $sign = quotemeta($sign.'inf');
1136 return 1 if ($x->{sign} =~ /^$sign$/);
1142 # return true if arg (BINT or num_str) is +1
1143 # or -1 if sign is given
1144 # we don't need $self, so undef instead of ref($_[0]) make it slightly faster
1145 my ($self,$x,$sign) = ref($_[0]) ? (undef,@_) : objectify(1,@_);
1147 $sign = '' if !defined $sign; $sign = '+' if $sign ne '-';
1149 return 0 if $x->{sign} ne $sign; # -1 != +1, NaN, +-inf aren't either
1150 $CALC->_is_one($x->{value});
1155 # return true when arg (BINT or num_str) is odd, false for even
1156 # we don't need $self, so undef instead of ref($_[0]) make it slightly faster
1157 my ($self,$x) = ref($_[0]) ? (undef,$_[0]) : objectify(1,@_);
1159 return 0 if $x->{sign} !~ /^[+-]$/; # NaN & +-inf aren't
1160 $CALC->_is_odd($x->{value});
1165 # return true when arg (BINT or num_str) is even, false for odd
1166 # we don't need $self, so undef instead of ref($_[0]) make it slightly faster
1167 my ($self,$x) = ref($_[0]) ? (undef,$_[0]) : objectify(1,@_);
1169 return 0 if $x->{sign} !~ /^[+-]$/; # NaN & +-inf aren't
1170 $CALC->_is_even($x->{value});
1175 # return true when arg (BINT or num_str) is positive (>= 0)
1176 # we don't need $self, so undef instead of ref($_[0]) make it slightly faster
1177 my ($self,$x) = ref($_[0]) ? (undef,$_[0]) : objectify(1,@_);
1179 return 1 if $x->{sign} =~ /^\+/;
1185 # return true when arg (BINT or num_str) is negative (< 0)
1186 # we don't need $self, so undef instead of ref($_[0]) make it slightly faster
1187 my ($self,$x) = ref($_[0]) ? (undef,$_[0]) : objectify(1,@_);
1189 return 1 if ($x->{sign} =~ /^-/);
1195 # return true when arg (BINT or num_str) is an integer
1196 # always true for BigInt, but different for Floats
1197 # we don't need $self, so undef instead of ref($_[0]) make it slightly faster
1198 my ($self,$x) = ref($_[0]) ? (undef,$_[0]) : objectify(1,@_);
1200 $x->{sign} =~ /^[+-]$/ ? 1 : 0; # inf/-inf/NaN aren't
1203 ###############################################################################
1207 # multiply two numbers -- stolen from Knuth Vol 2 pg 233
1208 # (BINT or num_str, BINT or num_str) return BINT
1209 my ($self,$x,$y,@r) = objectify(2,@_);
1211 return $x if $x->modify('bmul');
1213 return $x->bnan() if (($x->{sign} eq $nan) || ($y->{sign} eq $nan));
1216 if (($x->{sign} =~ /^[+-]inf$/) || ($y->{sign} =~ /^[+-]inf$/))
1218 return $x->bnan() if $x->is_zero() || $y->is_zero();
1219 # result will always be +-inf:
1220 # +inf * +/+inf => +inf, -inf * -/-inf => +inf
1221 # +inf * -/-inf => -inf, -inf * +/+inf => -inf
1222 return $x->binf() if ($x->{sign} =~ /^\+/ && $y->{sign} =~ /^\+/);
1223 return $x->binf() if ($x->{sign} =~ /^-/ && $y->{sign} =~ /^-/);
1224 return $x->binf('-');
1227 return $upgrade->bmul($x,$y,@r)
1228 if defined $upgrade && $y->isa($upgrade);
1230 $r[3] = $y; # no push here
1232 $x->{sign} = $x->{sign} eq $y->{sign} ? '+' : '-'; # +1 * +1 or -1 * -1 => +
1234 $x->{value} = $CALC->_mul($x->{value},$y->{value}); # do actual math
1235 $x->{sign} = '+' if $CALC->_is_zero($x->{value}); # no -0
1241 # helper function that handles +-inf cases for bdiv()/bmod() to reuse code
1242 my ($self,$x,$y) = @_;
1244 # NaN if x == NaN or y == NaN or x==y==0
1245 return wantarray ? ($x->bnan(),$self->bnan()) : $x->bnan()
1246 if (($x->is_nan() || $y->is_nan()) ||
1247 ($x->is_zero() && $y->is_zero()));
1249 # +-inf / +-inf == NaN, reminder also NaN
1250 if (($x->{sign} =~ /^[+-]inf$/) && ($y->{sign} =~ /^[+-]inf$/))
1252 return wantarray ? ($x->bnan(),$self->bnan()) : $x->bnan();
1254 # x / +-inf => 0, remainder x (works even if x == 0)
1255 if ($y->{sign} =~ /^[+-]inf$/)
1257 my $t = $x->copy(); # binf clobbers up $x
1258 return wantarray ? ($x->bzero(),$t) : $x->bzero()
1261 # 5 / 0 => +inf, -6 / 0 => -inf
1262 # +inf / 0 = inf, inf, and -inf / 0 => -inf, -inf
1263 # exception: -8 / 0 has remainder -8, not 8
1264 # exception: -inf / 0 has remainder -inf, not inf
1267 # +-inf / 0 => special case for -inf
1268 return wantarray ? ($x,$x->copy()) : $x if $x->is_inf();
1269 if (!$x->is_zero() && !$x->is_inf())
1271 my $t = $x->copy(); # binf clobbers up $x
1273 ($x->binf($x->{sign}),$t) : $x->binf($x->{sign})
1277 # last case: +-inf / ordinary number
1279 $sign = '-inf' if substr($x->{sign},0,1) ne $y->{sign};
1281 return wantarray ? ($x,$self->bzero()) : $x;
1286 # (dividend: BINT or num_str, divisor: BINT or num_str) return
1287 # (BINT,BINT) (quo,rem) or BINT (only rem)
1288 my ($self,$x,$y,@r) = objectify(2,@_);
1290 return $x if $x->modify('bdiv');
1292 return $self->_div_inf($x,$y)
1293 if (($x->{sign} !~ /^[+-]$/) || ($y->{sign} !~ /^[+-]$/) || $y->is_zero());
1295 return $upgrade->bdiv($upgrade->new($x),$y,@r)
1296 if defined $upgrade && !$y->isa($self);
1298 $r[3] = $y; # no push!
1302 wantarray ? ($x->round(@r),$self->bzero(@r)):$x->round(@r) if $x->is_zero();
1304 # Is $x in the interval [0, $y) (aka $x <= $y) ?
1305 my $cmp = $CALC->_acmp($x->{value},$y->{value});
1306 if (($cmp < 0) and (($x->{sign} eq $y->{sign}) or !wantarray))
1308 return $upgrade->bdiv($upgrade->new($x),$upgrade->new($y),@r)
1309 if defined $upgrade;
1311 return $x->bzero()->round(@r) unless wantarray;
1312 my $t = $x->copy(); # make copy first, because $x->bzero() clobbers $x
1313 return ($x->bzero()->round(@r),$t);
1317 # shortcut, both are the same, so set to +/- 1
1318 $x->__one( ($x->{sign} ne $y->{sign} ? '-' : '+') );
1319 return $x unless wantarray;
1320 return ($x->round(@r),$self->bzero(@r));
1322 return $upgrade->bdiv($upgrade->new($x),$upgrade->new($y),@r)
1323 if defined $upgrade;
1325 # calc new sign and in case $y == +/- 1, return $x
1326 my $xsign = $x->{sign}; # keep
1327 $x->{sign} = ($x->{sign} ne $y->{sign} ? '-' : '+');
1328 # check for / +-1 (cant use $y->is_one due to '-'
1329 if ($CALC->_is_one($y->{value}))
1331 return wantarray ? ($x->round(@r),$self->bzero(@r)) : $x->round(@r);
1336 my $rem = $self->bzero();
1337 ($x->{value},$rem->{value}) = $CALC->_div($x->{value},$y->{value});
1338 $x->{sign} = '+' if $CALC->_is_zero($x->{value});
1340 if (! $CALC->_is_zero($rem->{value}))
1342 $rem->{sign} = $y->{sign};
1343 $rem = $y-$rem if $xsign ne $y->{sign}; # one of them '-'
1347 $rem->{sign} = '+'; # dont leave -0
1353 $x->{value} = $CALC->_div($x->{value},$y->{value});
1354 $x->{sign} = '+' if $CALC->_is_zero($x->{value});
1360 # modulus (or remainder)
1361 # (BINT or num_str, BINT or num_str) return BINT
1362 my ($self,$x,$y,@r) = objectify(2,@_);
1364 return $x if $x->modify('bmod');
1365 $r[3] = $y; # no push!
1366 if (($x->{sign} !~ /^[+-]$/) || ($y->{sign} !~ /^[+-]$/) || $y->is_zero())
1368 my ($d,$r) = $self->_div_inf($x,$y);
1369 return $r->round(@r);
1372 if ($CALC->can('_mod'))
1374 # calc new sign and in case $y == +/- 1, return $x
1375 $x->{value} = $CALC->_mod($x->{value},$y->{value});
1376 if (!$CALC->_is_zero($x->{value}))
1378 my $xsign = $x->{sign};
1379 $x->{sign} = $y->{sign};
1380 $x = $y-$x if $xsign ne $y->{sign}; # one of them '-'
1384 $x->{sign} = '+'; # dont leave -0
1386 return $x->round(@r);
1388 my ($t,$rem) = $self->bdiv($x->copy(),$y,@r); # slow way (also rounds)
1390 foreach (qw/value sign _a _p/)
1392 $x->{$_} = $rem->{$_};
1399 # (BINT or num_str, BINT or num_str) return BINT
1400 # compute factorial numbers
1401 # modifies first argument
1402 my ($self,$x,@r) = objectify(1,@_);
1404 return $x if $x->modify('bfac');
1406 return $x->bnan() if $x->{sign} ne '+'; # inf, NnN, <0 etc => NaN
1407 return $x->bone(@r) if $x->is_zero() || $x->is_one(); # 0 or 1 => 1
1409 if ($CALC->can('_fac'))
1411 $x->{value} = $CALC->_fac($x->{value});
1412 return $x->round(@r);
1417 my $f = $self->new(2);
1418 while ($f->bacmp($n) < 0)
1420 $x->bmul($f); $f->binc();
1422 $x->bmul($f); # last step
1423 $x->round(@r); # round
1428 # (BINT or num_str, BINT or num_str) return BINT
1429 # compute power of two numbers -- stolen from Knuth Vol 2 pg 233
1430 # modifies first argument
1431 my ($self,$x,$y,@r) = objectify(2,@_);
1433 return $x if $x->modify('bpow');
1435 return $upgrade->bpow($upgrade->new($x),$y,@r)
1436 if defined $upgrade && !$y->isa($self);
1438 $r[3] = $y; # no push!
1439 return $x if $x->{sign} =~ /^[+-]inf$/; # -inf/+inf ** x
1440 return $x->bnan() if $x->{sign} eq $nan || $y->{sign} eq $nan;
1441 return $x->bone(@r) if $y->is_zero();
1442 return $x->round(@r) if $x->is_one() || $y->is_one();
1443 if ($x->{sign} eq '-' && $CALC->_is_one($x->{value}))
1445 # if $x == -1 and odd/even y => +1/-1
1446 return $y->is_odd() ? $x->round(@r) : $x->babs()->round(@r);
1447 # my Casio FX-5500L has a bug here: -1 ** 2 is -1, but -1 * -1 is 1;
1449 # 1 ** -y => 1 / (1 ** |y|)
1450 # so do test for negative $y after above's clause
1451 return $x->bnan() if $y->{sign} eq '-';
1452 return $x->round(@r) if $x->is_zero(); # 0**y => 0 (if not y <= 0)
1454 if ($CALC->can('_pow'))
1456 $x->{value} = $CALC->_pow($x->{value},$y->{value});
1457 return $x->round(@r);
1460 # based on the assumption that shifting in base 10 is fast, and that mul
1461 # works faster if numbers are small: we count trailing zeros (this step is
1462 # O(1)..O(N), but in case of O(N) we save much more time due to this),
1463 # stripping them out of the multiplication, and add $count * $y zeros
1464 # afterwards like this:
1465 # 300 ** 3 == 300*300*300 == 3*3*3 . '0' x 2 * 3 == 27 . '0' x 6
1466 # creates deep recursion?
1467 # my $zeros = $x->_trailing_zeros();
1470 # $x->brsft($zeros,10); # remove zeros
1471 # $x->bpow($y); # recursion (will not branch into here again)
1472 # $zeros = $y * $zeros; # real number of zeros to add
1473 # $x->blsft($zeros,10);
1474 # return $x->round($a,$p,$r);
1477 my $pow2 = $self->__one();
1478 my $y1 = $class->new($y);
1479 my $two = $self->new(2);
1480 while (!$y1->is_one())
1482 $pow2->bmul($x) if $y1->is_odd();
1486 $x->bmul($pow2) unless $pow2->is_one();
1492 # (BINT or num_str, BINT or num_str) return BINT
1493 # compute x << y, base n, y >= 0
1494 my ($self,$x,$y,$n,$a,$p,$r) = objectify(2,@_);
1496 return $x if $x->modify('blsft');
1497 return $x->bnan() if ($x->{sign} !~ /^[+-]$/ || $y->{sign} !~ /^[+-]$/);
1498 return $x->round($a,$p,$r) if $y->is_zero();
1500 $n = 2 if !defined $n; return $x->bnan() if $n <= 0 || $y->{sign} eq '-';
1502 my $t; $t = $CALC->_lsft($x->{value},$y->{value},$n) if $CALC->can('_lsft');
1505 $x->{value} = $t; return $x->round($a,$p,$r);
1508 return $x->bmul( $self->bpow($n, $y, $a, $p, $r), $a, $p, $r );
1513 # (BINT or num_str, BINT or num_str) return BINT
1514 # compute x >> y, base n, y >= 0
1515 my ($self,$x,$y,$n,$a,$p,$r) = objectify(2,@_);
1517 return $x if $x->modify('brsft');
1518 return $x->bnan() if ($x->{sign} !~ /^[+-]$/ || $y->{sign} !~ /^[+-]$/);
1519 return $x->round($a,$p,$r) if $y->is_zero();
1520 return $x->bzero($a,$p,$r) if $x->is_zero(); # 0 => 0
1522 $n = 2 if !defined $n; return $x->bnan() if $n <= 0 || $y->{sign} eq '-';
1524 # this only works for negative numbers when shifting in base 2
1525 if (($x->{sign} eq '-') && ($n == 2))
1527 return $x->round($a,$p,$r) if $x->is_one('-'); # -1 => -1
1530 # although this is O(N*N) in calc (as_bin!) it is O(N) in Pari et al
1531 # but perhaps there is a better emulation for two's complement shift...
1532 # if $y != 1, we must simulate it by doing:
1533 # convert to bin, flip all bits, shift, and be done
1534 $x->binc(); # -3 => -2
1535 my $bin = $x->as_bin();
1536 $bin =~ s/^-0b//; # strip '-0b' prefix
1537 $bin =~ tr/10/01/; # flip bits
1539 if (CORE::length($bin) <= $y)
1541 $bin = '0'; # shifting to far right creates -1
1542 # 0, because later increment makes
1543 # that 1, attached '-' makes it '-1'
1544 # because -1 >> x == -1 !
1548 $bin =~ s/.{$y}$//; # cut off at the right side
1549 $bin = '1' . $bin; # extend left side by one dummy '1'
1550 $bin =~ tr/10/01/; # flip bits back
1552 my $res = $self->new('0b'.$bin); # add prefix and convert back
1553 $res->binc(); # remember to increment
1554 $x->{value} = $res->{value}; # take over value
1555 return $x->round($a,$p,$r); # we are done now, magic, isn't?
1557 $x->bdec(); # n == 2, but $y == 1: this fixes it
1560 my $t; $t = $CALC->_rsft($x->{value},$y->{value},$n) if $CALC->can('_rsft');
1564 return $x->round($a,$p,$r);
1567 $x->bdiv($self->bpow($n,$y, $a,$p,$r), $a,$p,$r);
1573 #(BINT or num_str, BINT or num_str) return BINT
1575 my ($self,$x,$y,$a,$p,$r) = objectify(2,@_);
1577 return $x if $x->modify('band');
1579 local $Math::BigInt::upgrade = undef;
1581 return $x->bnan() if ($x->{sign} !~ /^[+-]$/ || $y->{sign} !~ /^[+-]$/);
1582 return $x->bzero() if $y->is_zero() || $x->is_zero();
1584 my $sign = 0; # sign of result
1585 $sign = 1 if ($x->{sign} eq '-') && ($y->{sign} eq '-');
1586 my $sx = 1; $sx = -1 if $x->{sign} eq '-';
1587 my $sy = 1; $sy = -1 if $y->{sign} eq '-';
1589 if ($CALC->can('_and') && $sx == 1 && $sy == 1)
1591 $x->{value} = $CALC->_and($x->{value},$y->{value});
1592 return $x->round($a,$p,$r);
1595 my $m = $self->bone(); my ($xr,$yr);
1596 my $x10000 = $self->new (0x1000);
1597 my $y1 = copy(ref($x),$y); # make copy
1598 $y1->babs(); # and positive
1599 my $x1 = $x->copy()->babs(); $x->bzero(); # modify x in place!
1600 use integer; # need this for negative bools
1601 while (!$x1->is_zero() && !$y1->is_zero())
1603 ($x1, $xr) = bdiv($x1, $x10000);
1604 ($y1, $yr) = bdiv($y1, $x10000);
1605 # make both op's numbers!
1606 $x->badd( bmul( $class->new(
1607 abs($sx*int($xr->numify()) & $sy*int($yr->numify()))),
1611 $x->bneg() if $sign;
1612 return $x->round($a,$p,$r);
1617 #(BINT or num_str, BINT or num_str) return BINT
1619 my ($self,$x,$y,$a,$p,$r) = objectify(2,@_);
1621 return $x if $x->modify('bior');
1623 local $Math::BigInt::upgrade = undef;
1625 return $x->bnan() if ($x->{sign} !~ /^[+-]$/ || $y->{sign} !~ /^[+-]$/);
1626 return $x if $y->is_zero();
1628 my $sign = 0; # sign of result
1629 $sign = 1 if ($x->{sign} eq '-') || ($y->{sign} eq '-');
1630 my $sx = 1; $sx = -1 if $x->{sign} eq '-';
1631 my $sy = 1; $sy = -1 if $y->{sign} eq '-';
1633 # don't use lib for negative values
1634 if ($CALC->can('_or') && $sx == 1 && $sy == 1)
1636 $x->{value} = $CALC->_or($x->{value},$y->{value});
1637 return $x->round($a,$p,$r);
1640 my $m = $self->bone(); my ($xr,$yr);
1641 my $x10000 = $self->new(0x10000);
1642 my $y1 = copy(ref($x),$y); # make copy
1643 $y1->babs(); # and positive
1644 my $x1 = $x->copy()->babs(); $x->bzero(); # modify x in place!
1645 use integer; # need this for negative bools
1646 while (!$x1->is_zero() || !$y1->is_zero())
1648 ($x1, $xr) = bdiv($x1,$x10000);
1649 ($y1, $yr) = bdiv($y1,$x10000);
1650 # make both op's numbers!
1651 $x->badd( bmul( $class->new(
1652 abs($sx*int($xr->numify()) | $sy*int($yr->numify()))),
1656 $x->bneg() if $sign;
1657 return $x->round($a,$p,$r);
1662 #(BINT or num_str, BINT or num_str) return BINT
1664 my ($self,$x,$y,$a,$p,$r) = objectify(2,@_);
1666 return $x if $x->modify('bxor');
1668 local $Math::BigInt::upgrade = undef;
1670 return $x->bnan() if ($x->{sign} !~ /^[+-]$/ || $y->{sign} !~ /^[+-]$/);
1671 return $x if $y->is_zero();
1673 my $sign = 0; # sign of result
1674 $sign = 1 if $x->{sign} ne $y->{sign};
1675 my $sx = 1; $sx = -1 if $x->{sign} eq '-';
1676 my $sy = 1; $sy = -1 if $y->{sign} eq '-';
1678 # don't use lib for negative values
1679 if ($CALC->can('_xor') && $sx == 1 && $sy == 1)
1681 $x->{value} = $CALC->_xor($x->{value},$y->{value});
1682 return $x->round($a,$p,$r);
1685 my $m = $self->bone(); my ($xr,$yr);
1686 my $x10000 = $self->new(0x10000);
1687 my $y1 = copy(ref($x),$y); # make copy
1688 $y1->babs(); # and positive
1689 my $x1 = $x->copy()->babs(); $x->bzero(); # modify x in place!
1690 use integer; # need this for negative bools
1691 while (!$x1->is_zero() || !$y1->is_zero())
1693 ($x1, $xr) = bdiv($x1, $x10000);
1694 ($y1, $yr) = bdiv($y1, $x10000);
1695 # make both op's numbers!
1696 $x->badd( bmul( $class->new(
1697 abs($sx*int($xr->numify()) ^ $sy*int($yr->numify()))),
1701 $x->bneg() if $sign;
1702 return $x->round($a,$p,$r);
1707 my ($self,$x) = ref($_[0]) ? (ref($_[0]),$_[0]) : objectify(1,@_);
1709 my $e = $CALC->_len($x->{value});
1710 return wantarray ? ($e,0) : $e;
1715 # return the nth decimal digit, negative values count backward, 0 is right
1716 my ($self,$x,$n) = ref($_[0]) ? (ref($_[0]),@_) : objectify(1,@_);
1717 $n = 0 if !defined $n;
1719 $CALC->_digit($x->{value},$n);
1724 # return the amount of trailing zeros in $x
1726 $x = $class->new($x) unless ref $x;
1728 return 0 if $x->is_zero() || $x->is_odd() || $x->{sign} !~ /^[+-]$/;
1730 return $CALC->_zeros($x->{value}) if $CALC->can('_zeros');
1732 # if not: since we do not know underlying internal representation:
1733 my $es = "$x"; $es =~ /([0]*)$/;
1734 return 0 if !defined $1; # no zeros
1735 return CORE::length("$1"); # as string, not as +0!
1740 my ($self,$x,$a,$p,$r) = ref($_[0]) ? (ref($_[0]),$_[0]) : objectify(1,@_);
1742 return $x if $x->modify('bsqrt');
1744 return $x->bnan() if $x->{sign} ne '+'; # -x or inf or NaN => NaN
1745 return $x->bzero($a,$p) if $x->is_zero(); # 0 => 0
1746 return $x->round($a,$p,$r) if $x->is_one(); # 1 => 1
1748 return $upgrade->bsqrt($x,$a,$p,$r) if defined $upgrade;
1750 if ($CALC->can('_sqrt'))
1752 $x->{value} = $CALC->_sqrt($x->{value});
1753 return $x->round($a,$p,$r);
1756 return $x->bone($a,$p) if $x < 4; # 2,3 => 1
1758 my $l = int($x->length()/2);
1760 $x->bone(); # keep ref($x), but modify it
1763 my $last = $self->bzero();
1764 my $two = $self->new(2);
1765 my $lastlast = $x+$two;
1766 while ($last != $x && $lastlast != $x)
1768 $lastlast = $last; $last = $x;
1772 $x-- if $x * $x > $y; # overshot?
1773 $x->round($a,$p,$r);
1778 # return a copy of the exponent (here always 0, NaN or 1 for $m == 0)
1779 my ($self,$x) = ref($_[0]) ? (ref($_[0]),$_[0]) : objectify(1,@_);
1781 if ($x->{sign} !~ /^[+-]$/)
1783 my $s = $x->{sign}; $s =~ s/^[+-]//;
1784 return $self->new($s); # -inf,+inf => inf
1786 my $e = $class->bzero();
1787 return $e->binc() if $x->is_zero();
1788 $e += $x->_trailing_zeros();
1794 # return the mantissa (compatible to Math::BigFloat, e.g. reduced)
1795 my ($self,$x) = ref($_[0]) ? (ref($_[0]),$_[0]) : objectify(1,@_);
1797 if ($x->{sign} !~ /^[+-]$/)
1799 return $self->new($x->{sign}); # keep + or - sign
1802 # that's inefficient
1803 my $zeros = $m->_trailing_zeros();
1804 $m->brsft($zeros,10) if $zeros != 0;
1805 # $m /= 10 ** $zeros if $zeros != 0;
1811 # return a copy of both the exponent and the mantissa
1812 my ($self,$x) = ref($_[0]) ? (ref($_[0]),$_[0]) : objectify(1,@_);
1814 return ($x->mantissa(),$x->exponent());
1817 ##############################################################################
1818 # rounding functions
1822 # precision: round to the $Nth digit left (+$n) or right (-$n) from the '.'
1823 # $n == 0 || $n == 1 => round to integer
1824 my $x = shift; $x = $class->new($x) unless ref $x;
1825 my ($scale,$mode) = $x->_scale_p($x->precision(),$x->round_mode(),@_);
1826 return $x if !defined $scale; # no-op
1827 return $x if $x->modify('bfround');
1829 # no-op for BigInts if $n <= 0
1832 $x->{_a} = undef; # clear an eventual set A
1833 $x->{_p} = $scale; return $x;
1836 $x->bround( $x->length()-$scale, $mode);
1837 $x->{_a} = undef; # bround sets {_a}
1838 $x->{_p} = $scale; # so correct it
1842 sub _scan_for_nonzero
1848 my $len = $x->length();
1849 return 0 if $len == 1; # '5' is trailed by invisible zeros
1850 my $follow = $pad - 1;
1851 return 0 if $follow > $len || $follow < 1;
1853 # since we do not know underlying represention of $x, use decimal string
1854 #my $r = substr ($$xs,-$follow);
1855 my $r = substr ("$x",-$follow);
1856 return 1 if $r =~ /[^0]/; return 0;
1861 # to make life easier for switch between MBF and MBI (autoload fxxx()
1862 # like MBF does for bxxx()?)
1864 return $x->bround(@_);
1869 # accuracy: +$n preserve $n digits from left,
1870 # -$n preserve $n digits from right (f.i. for 0.1234 style in MBF)
1872 # and overwrite the rest with 0's, return normalized number
1873 # do not return $x->bnorm(), but $x
1875 my $x = shift; $x = $class->new($x) unless ref $x;
1876 my ($scale,$mode) = $x->_scale_a($x->accuracy(),$x->round_mode(),@_);
1877 return $x if !defined $scale; # no-op
1878 return $x if $x->modify('bround');
1880 if ($x->is_zero() || $scale == 0)
1882 $x->{_a} = $scale if !defined $x->{_a} || $x->{_a} > $scale; # 3 > 2
1885 return $x if $x->{sign} !~ /^[+-]$/; # inf, NaN
1887 # we have fewer digits than we want to scale to
1888 my $len = $x->length();
1889 # scale < 0, but > -len (not >=!)
1890 if (($scale < 0 && $scale < -$len-1) || ($scale >= $len))
1892 $x->{_a} = $scale if !defined $x->{_a} || $x->{_a} > $scale; # 3 > 2
1896 # count of 0's to pad, from left (+) or right (-): 9 - +6 => 3, or |-6| => 6
1897 my ($pad,$digit_round,$digit_after);
1898 $pad = $len - $scale;
1899 $pad = abs($scale-1) if $scale < 0;
1901 # do not use digit(), it is costly for binary => decimal
1903 my $xs = $CALC->_str($x->{value});
1906 # pad: 123: 0 => -1, at 1 => -2, at 2 => -3, at 3 => -4
1907 # pad+1: 123: 0 => 0, at 1 => -1, at 2 => -2, at 3 => -3
1908 $digit_round = '0'; $digit_round = substr($$xs,$pl,1) if $pad <= $len;
1909 $pl++; $pl ++ if $pad >= $len;
1910 $digit_after = '0'; $digit_after = substr($$xs,$pl,1) if $pad > 0;
1912 # print "$pad $pl $$xs dr $digit_round da $digit_after\n";
1914 # in case of 01234 we round down, for 6789 up, and only in case 5 we look
1915 # closer at the remaining digits of the original $x, remember decision
1916 my $round_up = 1; # default round up
1918 ($mode eq 'trunc') || # trunc by round down
1919 ($digit_after =~ /[01234]/) || # round down anyway,
1921 ($digit_after eq '5') && # not 5000...0000
1922 ($x->_scan_for_nonzero($pad,$xs) == 0) &&
1924 ($mode eq 'even') && ($digit_round =~ /[24680]/) ||
1925 ($mode eq 'odd') && ($digit_round =~ /[13579]/) ||
1926 ($mode eq '+inf') && ($x->{sign} eq '-') ||
1927 ($mode eq '-inf') && ($x->{sign} eq '+') ||
1928 ($mode eq 'zero') # round down if zero, sign adjusted below
1930 my $put_back = 0; # not yet modified
1932 # old code, depend on internal representation
1933 # split mantissa at $pad and then pad with zeros
1934 #my $s5 = int($pad / 5);
1938 # $x->{value}->[$i++] = 0; # replace with 5 x 0
1940 #$x->{value}->[$s5] = '00000'.$x->{value}->[$s5]; # pad with 0
1941 #my $rem = $pad % 5; # so much left over
1944 # #print "remainder $rem\n";
1945 ## #print "elem $x->{value}->[$s5]\n";
1946 # substr($x->{value}->[$s5],-$rem,$rem) = '0' x $rem; # stamp w/ '0'
1948 #$x->{value}->[$s5] = int ($x->{value}->[$s5]); # str '05' => int '5'
1949 #print ${$CALC->_str($pad->{value})}," $len\n";
1951 if (($pad > 0) && ($pad <= $len))
1953 substr($$xs,-$pad,$pad) = '0' x $pad;
1958 $x->bzero(); # round to '0'
1961 if ($round_up) # what gave test above?
1964 $pad = $len, $$xs = '0'x$pad if $scale < 0; # tlr: whack 0.51=>1.0
1966 # we modify directly the string variant instead of creating a number and
1968 my $c = 0; $pad ++; # for $pad == $len case
1969 while ($pad <= $len)
1971 $c = substr($$xs,-$pad,1) + 1; $c = '0' if $c eq '10';
1972 substr($$xs,-$pad,1) = $c; $pad++;
1973 last if $c != 0; # no overflow => early out
1975 $$xs = '1'.$$xs if $c == 0;
1977 # $x->badd( Math::BigInt->new($x->{sign}.'1'. '0' x $pad) );
1979 $x->{value} = $CALC->_new($xs) if $put_back == 1; # put back in
1981 $x->{_a} = $scale if $scale >= 0;
1984 $x->{_a} = $len+$scale;
1985 $x->{_a} = 0 if $scale < -$len;
1992 # return integer less or equal then number, since it is already integer,
1993 # always returns $self
1994 my ($self,$x,$a,$p,$r) = ref($_[0]) ? (ref($_[0]),@_) : objectify(1,@_);
1996 # not needed: return $x if $x->modify('bfloor');
1997 return $x->round($a,$p,$r);
2002 # return integer greater or equal then number, since it is already integer,
2003 # always returns $self
2004 my ($self,$x,$a,$p,$r) = ref($_[0]) ? (ref($_[0]),@_) : objectify(1,@_);
2006 # not needed: return $x if $x->modify('bceil');
2007 return $x->round($a,$p,$r);
2010 ##############################################################################
2011 # private stuff (internal use only)
2015 # internal speedup, set argument to 1, or create a +/- 1
2017 my $x = $self->bone(); # $x->{value} = $CALC->_one();
2018 $x->{sign} = shift || '+';
2024 # Overload will swap params if first one is no object ref so that the first
2025 # one is always an object ref. In this case, third param is true.
2026 # This routine is to overcome the effect of scalar,$object creating an object
2027 # of the class of this package, instead of the second param $object. This
2028 # happens inside overload, when the overload section of this package is
2029 # inherited by sub classes.
2030 # For overload cases (and this is used only there), we need to preserve the
2031 # args, hence the copy().
2032 # You can override this method in a subclass, the overload section will call
2033 # $object->_swap() to make sure it arrives at the proper subclass, with some
2034 # exceptions like '+' and '-'. To make '+' and '-' work, you also need to
2035 # specify your own overload for them.
2037 # object, (object|scalar) => preserve first and make copy
2038 # scalar, object => swapped, re-swap and create new from first
2039 # (using class of second object, not $class!!)
2040 my $self = shift; # for override in subclass
2043 my $c = ref ($_[0]) || $class; # fallback $class should not happen
2044 return ( $c->new($_[1]), $_[0] );
2046 return ( $_[0]->copy(), $_[1] );
2051 # check for strings, if yes, return objects instead
2053 # the first argument is number of args objectify() should look at it will
2054 # return $count+1 elements, the first will be a classname. This is because
2055 # overloaded '""' calls bstr($object,undef,undef) and this would result in
2056 # useless objects beeing created and thrown away. So we cannot simple loop
2057 # over @_. If the given count is 0, all arguments will be used.
2059 # If the second arg is a ref, use it as class.
2060 # If not, try to use it as classname, unless undef, then use $class
2061 # (aka Math::BigInt). The latter shouldn't happen,though.
2064 # $x->badd(1); => ref x, scalar y
2065 # Class->badd(1,2); => classname x (scalar), scalar x, scalar y
2066 # Class->badd( Class->(1),2); => classname x (scalar), ref x, scalar y
2067 # Math::BigInt::badd(1,2); => scalar x, scalar y
2068 # In the last case we check number of arguments to turn it silently into
2069 # $class,1,2. (We can not take '1' as class ;o)
2070 # badd($class,1) is not supported (it should, eventually, try to add undef)
2071 # currently it tries 'Math::BigInt' + 1, which will not work.
2073 # some shortcut for the common cases
2075 return (ref($_[1]),$_[1]) if (@_ == 2) && ($_[0]||0 == 1) && ref($_[1]);
2077 my $count = abs(shift || 0);
2079 my (@a,$k,$d); # resulting array, temp, and downgrade
2082 # okay, got object as first
2087 # nope, got 1,2 (Class->xxx(1) => Class,1 and not supported)
2089 $a[0] = shift if $_[0] =~ /^[A-Z].*::/; # classname as first?
2093 # disable downgrading, because Math::BigFLoat->foo('1.0','2.0') needs floats
2094 if (defined ${"$a[0]::downgrade"})
2096 $d = ${"$a[0]::downgrade"};
2097 ${"$a[0]::downgrade"} = undef;
2100 # print "Now in objectify, my class is today $a[0]\n";
2108 $k = $a[0]->new($k);
2110 elsif (ref($k) ne $a[0])
2112 # foreign object, try to convert to integer
2113 $k->can('as_number') ? $k = $k->as_number() : $k = $a[0]->new($k);
2126 $k = $a[0]->new($k);
2128 elsif (ref($k) ne $a[0])
2130 # foreign object, try to convert to integer
2131 $k->can('as_number') ? $k = $k->as_number() : $k = $a[0]->new($k);
2135 push @a,@_; # return other params, too
2137 die "$class objectify needs list context" unless wantarray;
2138 ${"$a[0]::downgrade"} = $d;
2147 my @a; my $l = scalar @_;
2148 for ( my $i = 0; $i < $l ; $i++ )
2150 # print "at $_[$i]\n";
2151 if ($_[$i] eq ':constant')
2153 # this causes overlord er load to step in
2154 overload::constant integer => sub { $self->new(shift) };
2155 overload::constant binary => sub { $self->new(shift) };
2157 elsif ($_[$i] eq 'upgrade')
2159 # this causes upgrading
2160 $upgrade = $_[$i+1]; # or undef to disable
2163 elsif ($_[$i] =~ /^lib$/i)
2165 # this causes a different low lib to take care...
2166 $CALC = $_[$i+1] || '';
2175 # any non :constant stuff is handled by our parent, Exporter
2176 # even if @_ is empty, to give it a chance
2177 $self->SUPER::import(@a); # need it for subclasses
2178 $self->export_to_level(1,$self,@a); # need it for MBF
2180 # try to load core math lib
2181 my @c = split /\s*,\s*/,$CALC;
2182 push @c,'Calc'; # if all fail, try this
2183 $CALC = ''; # signal error
2184 foreach my $lib (@c)
2186 $lib = 'Math::BigInt::'.$lib if $lib !~ /^Math::BigInt/i;
2190 # Perl < 5.6.0 dies with "out of memory!" when eval() and ':constant' is
2191 # used in the same script, or eval inside import().
2192 (my $mod = $lib . '.pm') =~ s!::!/!g;
2193 # require does not automatically :: => /, so portability problems arise
2194 eval { require $mod; $lib->import( @c ); }
2198 eval "use $lib qw/@c/;";
2200 $CALC = $lib, last if $@ eq ''; # no error in loading lib?
2202 die "Couldn't load any math lib, not even the default" if $CALC eq '';
2207 # convert a (ref to) big hex string to BigInt, return undef for error
2210 my $x = Math::BigInt->bzero();
2213 $$hs =~ s/([0-9a-fA-F])_([0-9a-fA-F])/$1$2/g;
2214 $$hs =~ s/([0-9a-fA-F])_([0-9a-fA-F])/$1$2/g;
2216 return $x->bnan() if $$hs !~ /^[\-\+]?0x[0-9A-Fa-f]+$/;
2218 my $sign = '+'; $sign = '-' if ($$hs =~ /^-/);
2220 $$hs =~ s/^[+-]//; # strip sign
2221 if ($CALC->can('_from_hex'))
2223 $x->{value} = $CALC->_from_hex($hs);
2227 # fallback to pure perl
2228 my $mul = Math::BigInt->bzero(); $mul++;
2229 my $x65536 = Math::BigInt->new(65536);
2230 my $len = CORE::length($$hs)-2;
2231 $len = int($len/4); # 4-digit parts, w/o '0x'
2232 my $val; my $i = -4;
2235 $val = substr($$hs,$i,4);
2236 $val =~ s/^[+-]?0x// if $len == 0; # for last part only because
2237 $val = hex($val); # hex does not like wrong chars
2239 $x += $mul * $val if $val != 0;
2240 $mul *= $x65536 if $len >= 0; # skip last mul
2243 $x->{sign} = $sign unless $CALC->_is_zero($x->{value}); # no '-0'
2249 # convert a (ref to) big binary string to BigInt, return undef for error
2252 my $x = Math::BigInt->bzero();
2254 $$bs =~ s/([01])_([01])/$1$2/g;
2255 $$bs =~ s/([01])_([01])/$1$2/g;
2256 return $x->bnan() if $$bs !~ /^[+-]?0b[01]+$/;
2258 my $sign = '+'; $sign = '-' if ($$bs =~ /^\-/);
2259 $$bs =~ s/^[+-]//; # strip sign
2260 if ($CALC->can('_from_bin'))
2262 $x->{value} = $CALC->_from_bin($bs);
2266 my $mul = Math::BigInt->bzero(); $mul++;
2267 my $x256 = Math::BigInt->new(256);
2268 my $len = CORE::length($$bs)-2;
2269 $len = int($len/8); # 8-digit parts, w/o '0b'
2270 my $val; my $i = -8;
2273 $val = substr($$bs,$i,8);
2274 $val =~ s/^[+-]?0b// if $len == 0; # for last part only
2275 #$val = oct('0b'.$val); # does not work on Perl prior to 5.6.0
2277 # $val = ('0' x (8-CORE::length($val))).$val if CORE::length($val) < 8;
2278 $val = ord(pack('B8',substr('00000000'.$val,-8,8)));
2280 $x += $mul * $val if $val != 0;
2281 $mul *= $x256 if $len >= 0; # skip last mul
2284 $x->{sign} = $sign unless $CALC->_is_zero($x->{value}); # no '-0'
2290 # (ref to num_str) return num_str
2291 # internal, take apart a string and return the pieces
2292 # strip leading/trailing whitespace, leading zeros, underscore and reject
2296 # strip white space at front, also extranous leading zeros
2297 $$x =~ s/^\s*([-]?)0*([0-9])/$1$2/g; # will not strip ' .2'
2298 $$x =~ s/^\s+//; # but this will
2299 $$x =~ s/\s+$//g; # strip white space at end
2301 # shortcut, if nothing to split, return early
2302 if ($$x =~ /^[+-]?\d+$/)
2304 $$x =~ s/^([+-])0*([0-9])/$2/; my $sign = $1 || '+';
2305 return (\$sign, $x, \'', \'', \0);
2308 # invalid starting char?
2309 return if $$x !~ /^[+-]?(\.?[0-9]|0b[0-1]|0x[0-9a-fA-F])/;
2311 return __from_hex($x) if $$x =~ /^[\-\+]?0x/; # hex string
2312 return __from_bin($x) if $$x =~ /^[\-\+]?0b/; # binary string
2314 # strip underscores between digits
2315 $$x =~ s/(\d)_(\d)/$1$2/g;
2316 $$x =~ s/(\d)_(\d)/$1$2/g; # do twice for 1_2_3
2318 # some possible inputs:
2319 # 2.1234 # 0.12 # 1 # 1E1 # 2.134E1 # 434E-10 # 1.02009E-2
2320 # .2 # 1_2_3.4_5_6 # 1.4E1_2_3 # 1e3 # +.2
2322 return if $$x =~ /[Ee].*[Ee]/; # more than one E => error
2324 my ($m,$e) = split /[Ee]/,$$x;
2325 $e = '0' if !defined $e || $e eq "";
2326 # sign,value for exponent,mantint,mantfrac
2327 my ($es,$ev,$mis,$miv,$mfv);
2329 if ($e =~ /^([+-]?)0*(\d+)$/) # strip leading zeros
2333 return if $m eq '.' || $m eq '';
2334 my ($mi,$mf) = split /\./,$m;
2335 $mi = '0' if !defined $mi;
2336 $mi .= '0' if $mi =~ /^[\-\+]?$/;
2337 $mf = '0' if !defined $mf || $mf eq '';
2338 if ($mi =~ /^([+-]?)0*(\d+)$/) # strip leading zeros
2340 $mis = $1||'+'; $miv = $2;
2341 return unless ($mf =~ /^(\d*?)0*$/); # strip trailing zeros
2343 return (\$mis,\$miv,\$mfv,\$es,\$ev);
2346 return; # NaN, not a number
2351 # an object might be asked to return itself as bigint on certain overloaded
2352 # operations, this does exactly this, so that sub classes can simple inherit
2353 # it or override with their own integer conversion routine
2361 # return as hex string, with prefixed 0x
2362 my $x = shift; $x = $class->new($x) if !ref($x);
2364 return $x->bstr() if $x->{sign} !~ /^[+-]$/; # inf, nan etc
2365 return '0x0' if $x->is_zero();
2367 my $es = ''; my $s = '';
2368 $s = $x->{sign} if $x->{sign} eq '-';
2369 if ($CALC->can('_as_hex'))
2371 $es = ${$CALC->_as_hex($x->{value})};
2375 my $x1 = $x->copy()->babs(); my $xr;
2376 my $x10000 = Math::BigInt->new (0x10000);
2377 while (!$x1->is_zero())
2379 ($x1, $xr) = bdiv($x1,$x10000);
2380 $es .= unpack('h4',pack('v',$xr->numify()));
2383 $es =~ s/^[0]+//; # strip leading zeros
2391 # return as binary string, with prefixed 0b
2392 my $x = shift; $x = $class->new($x) if !ref($x);
2394 return $x->bstr() if $x->{sign} !~ /^[+-]$/; # inf, nan etc
2395 return '0b0' if $x->is_zero();
2397 my $es = ''; my $s = '';
2398 $s = $x->{sign} if $x->{sign} eq '-';
2399 if ($CALC->can('_as_bin'))
2401 $es = ${$CALC->_as_bin($x->{value})};
2405 my $x1 = $x->copy()->babs(); my $xr;
2406 my $x10000 = Math::BigInt->new (0x10000);
2407 while (!$x1->is_zero())
2409 ($x1, $xr) = bdiv($x1,$x10000);
2410 $es .= unpack('b16',pack('v',$xr->numify()));
2413 $es =~ s/^[0]+//; # strip leading zeros
2419 ##############################################################################
2420 # internal calculation routines (others are in Math::BigInt::Calc etc)
2424 # (BINT or num_str, BINT or num_str) return BINT
2425 # does modify first argument
2428 my $x = shift; my $ty = shift;
2429 return $x->bnan() if ($x->{sign} eq $nan) || ($ty->{sign} eq $nan);
2430 return $x * $ty / bgcd($x,$ty);
2435 # (BINT or num_str, BINT or num_str) return BINT
2436 # does modify both arguments
2437 # GCD -- Euclids algorithm E, Knuth Vol 2 pg 296
2440 return $x->bnan() if $x->{sign} !~ /^[+-]$/ || $ty->{sign} !~ /^[+-]$/;
2442 while (!$ty->is_zero())
2444 ($x, $ty) = ($ty,bmod($x,$ty));
2449 ###############################################################################
2450 # this method return 0 if the object can be modified, or 1 for not
2451 # We use a fast use constant statement here, to avoid costly calls. Subclasses
2452 # may override it with special code (f.i. Math::BigInt::Constant does so)
2454 sub modify () { 0; }
2461 Math::BigInt - Arbitrary size integer math package
2468 $x = Math::BigInt->new($str); # defaults to 0
2469 $nan = Math::BigInt->bnan(); # create a NotANumber
2470 $zero = Math::BigInt->bzero(); # create a +0
2471 $inf = Math::BigInt->binf(); # create a +inf
2472 $inf = Math::BigInt->binf('-'); # create a -inf
2473 $one = Math::BigInt->bone(); # create a +1
2474 $one = Math::BigInt->bone('-'); # create a -1
2477 $x->is_zero(); # true if arg is +0
2478 $x->is_nan(); # true if arg is NaN
2479 $x->is_one(); # true if arg is +1
2480 $x->is_one('-'); # true if arg is -1
2481 $x->is_odd(); # true if odd, false for even
2482 $x->is_even(); # true if even, false for odd
2483 $x->is_positive(); # true if >= 0
2484 $x->is_negative(); # true if < 0
2485 $x->is_inf(sign); # true if +inf, or -inf (sign is default '+')
2486 $x->is_int(); # true if $x is an integer (not a float)
2488 $x->bcmp($y); # compare numbers (undef,<0,=0,>0)
2489 $x->bacmp($y); # compare absolutely (undef,<0,=0,>0)
2490 $x->sign(); # return the sign, either +,- or NaN
2491 $x->digit($n); # return the nth digit, counting from right
2492 $x->digit(-$n); # return the nth digit, counting from left
2494 # The following all modify their first argument:
2497 $x->bzero(); # set $x to 0
2498 $x->bnan(); # set $x to NaN
2499 $x->bone(); # set $x to +1
2500 $x->bone('-'); # set $x to -1
2501 $x->binf(); # set $x to inf
2502 $x->binf('-'); # set $x to -inf
2504 $x->bneg(); # negation
2505 $x->babs(); # absolute value
2506 $x->bnorm(); # normalize (no-op)
2507 $x->bnot(); # two's complement (bit wise not)
2508 $x->binc(); # increment x by 1
2509 $x->bdec(); # decrement x by 1
2511 $x->badd($y); # addition (add $y to $x)
2512 $x->bsub($y); # subtraction (subtract $y from $x)
2513 $x->bmul($y); # multiplication (multiply $x by $y)
2514 $x->bdiv($y); # divide, set $x to quotient
2515 # return (quo,rem) or quo if scalar
2517 $x->bmod($y); # modulus (x % y)
2518 $x->bpow($y); # power of arguments (x ** y)
2519 $x->blsft($y); # left shift
2520 $x->brsft($y); # right shift
2521 $x->blsft($y,$n); # left shift, by base $n (like 10)
2522 $x->brsft($y,$n); # right shift, by base $n (like 10)
2524 $x->band($y); # bitwise and
2525 $x->bior($y); # bitwise inclusive or
2526 $x->bxor($y); # bitwise exclusive or
2527 $x->bnot(); # bitwise not (two's complement)
2529 $x->bsqrt(); # calculate square-root
2530 $x->bfac(); # factorial of $x (1*2*3*4*..$x)
2532 $x->round($A,$P,$round_mode); # round to accuracy or precision using mode $r
2533 $x->bround($N); # accuracy: preserve $N digits
2534 $x->bfround($N); # round to $Nth digit, no-op for BigInts
2536 # The following do not modify their arguments in BigInt, but do in BigFloat:
2537 $x->bfloor(); # return integer less or equal than $x
2538 $x->bceil(); # return integer greater or equal than $x
2540 # The following do not modify their arguments:
2542 bgcd(@values); # greatest common divisor (no OO style)
2543 blcm(@values); # lowest common multiplicator (no OO style)
2545 $x->length(); # return number of digits in number
2546 ($x,$f) = $x->length(); # length of number and length of fraction part,
2547 # latter is always 0 digits long for BigInt's
2549 $x->exponent(); # return exponent as BigInt
2550 $x->mantissa(); # return (signed) mantissa as BigInt
2551 $x->parts(); # return (mantissa,exponent) as BigInt
2552 $x->copy(); # make a true copy of $x (unlike $y = $x;)
2553 $x->as_number(); # return as BigInt (in BigInt: same as copy())
2555 # conversation to string
2556 $x->bstr(); # normalized string
2557 $x->bsstr(); # normalized string in scientific notation
2558 $x->as_hex(); # as signed hexadecimal string with prefixed 0x
2559 $x->as_bin(); # as signed binary string with prefixed 0b
2561 Math::BigInt->config(); # return hash containing configuration/version
2565 All operators (inlcuding basic math operations) are overloaded if you
2566 declare your big integers as
2568 $i = new Math::BigInt '123_456_789_123_456_789';
2570 Operations with overloaded operators preserve the arguments which is
2571 exactly what you expect.
2575 =item Canonical notation
2577 Big integer values are strings of the form C</^[+-]\d+$/> with leading
2580 '-0' canonical value '-0', normalized '0'
2581 ' -123_123_123' canonical value '-123123123'
2582 '1_23_456_7890' canonical value '1234567890'
2586 Input values to these routines may be either Math::BigInt objects or
2587 strings of the form C</^\s*[+-]?[\d]+\.?[\d]*E?[+-]?[\d]*$/>.
2589 You can include one underscore between any two digits.
2591 This means integer values like 1.01E2 or even 1000E-2 are also accepted.
2592 Non integer values result in NaN.
2594 Math::BigInt::new() defaults to 0, while Math::BigInt::new('') results
2597 bnorm() on a BigInt object is now effectively a no-op, since the numbers
2598 are always stored in normalized form. On a string, it creates a BigInt
2603 Output values are BigInt objects (normalized), except for bstr(), which
2604 returns a string in normalized form.
2605 Some routines (C<is_odd()>, C<is_even()>, C<is_zero()>, C<is_one()>,
2606 C<is_nan()>) return true or false, while others (C<bcmp()>, C<bacmp()>)
2607 return either undef, <0, 0 or >0 and are suited for sort.
2613 Each of the methods below accepts three additional parameters. These arguments
2614 $A, $P and $R are accuracy, precision and round_mode. Please see more in the
2615 section about ACCURACY and ROUNDIND.
2621 print Dumper ( Math::BigInt->config() );
2623 Returns a hash containing the configuration, e.g. the version number, lib
2628 $x->accuracy(5); # local for $x
2629 $class->accuracy(5); # global for all members of $class
2631 Set or get the global or local accuracy, aka how many significant digits the
2632 results have. Please see the section about L<ACCURACY AND PRECISION> for
2635 Value must be greater than zero. Pass an undef value to disable it:
2637 $x->accuracy(undef);
2638 Math::BigInt->accuracy(undef);
2640 Returns the current accuracy. For C<$x->accuracy()> it will return either the
2641 local accuracy, or if not defined, the global. This means the return value
2642 represents the accuracy that will be in effect for $x:
2644 $y = Math::BigInt->new(1234567); # unrounded
2645 print Math::BigInt->accuracy(4),"\n"; # set 4, print 4
2646 $x = Math::BigInt->new(123456); # will be automatically rounded
2647 print "$x $y\n"; # '123500 1234567'
2648 print $x->accuracy(),"\n"; # will be 4
2649 print $y->accuracy(),"\n"; # also 4, since global is 4
2650 print Math::BigInt->accuracy(5),"\n"; # set to 5, print 5
2651 print $x->accuracy(),"\n"; # still 4
2652 print $y->accuracy(),"\n"; # 5, since global is 5
2658 Shifts $x right by $y in base $n. Default is base 2, used are usually 10 and
2659 2, but others work, too.
2661 Right shifting usually amounts to dividing $x by $n ** $y and truncating the
2665 $x = Math::BigInt->new(10);
2666 $x->brsft(1); # same as $x >> 1: 5
2667 $x = Math::BigInt->new(1234);
2668 $x->brsft(2,10); # result 12
2670 There is one exception, and that is base 2 with negative $x:
2673 $x = Math::BigInt->new(-5);
2676 This will print -3, not -2 (as it would if you divide -5 by 2 and truncate the
2681 $x = Math::BigInt->new($str,$A,$P,$R);
2683 Creates a new BigInt object from a string or another BigInt object. The
2684 input is accepted as decimal, hex (with leading '0x') or binary (with leading
2689 $x = Math::BigInt->bnan();
2691 Creates a new BigInt object representing NaN (Not A Number).
2692 If used on an object, it will set it to NaN:
2698 $x = Math::BigInt->bzero();
2700 Creates a new BigInt object representing zero.
2701 If used on an object, it will set it to zero:
2707 $x = Math::BigInt->binf($sign);
2709 Creates a new BigInt object representing infinity. The optional argument is
2710 either '-' or '+', indicating whether you want infinity or minus infinity.
2711 If used on an object, it will set it to infinity:
2718 $x = Math::BigInt->binf($sign);
2720 Creates a new BigInt object representing one. The optional argument is
2721 either '-' or '+', indicating whether you want one or minus one.
2722 If used on an object, it will set it to one:
2727 =head2 is_one()/is_zero()/is_nan()/is_inf()
2730 $x->is_zero(); # true if arg is +0
2731 $x->is_nan(); # true if arg is NaN
2732 $x->is_one(); # true if arg is +1
2733 $x->is_one('-'); # true if arg is -1
2734 $x->is_inf(); # true if +inf
2735 $x->is_inf('-'); # true if -inf (sign is default '+')
2737 These methods all test the BigInt for beeing one specific value and return
2738 true or false depending on the input. These are faster than doing something
2743 =head2 is_positive()/is_negative()
2745 $x->is_positive(); # true if >= 0
2746 $x->is_negative(); # true if < 0
2748 The methods return true if the argument is positive or negative, respectively.
2749 C<NaN> is neither positive nor negative, while C<+inf> counts as positive, and
2750 C<-inf> is negative. A C<zero> is positive.
2752 These methods are only testing the sign, and not the value.
2754 =head2 is_odd()/is_even()/is_int()
2756 $x->is_odd(); # true if odd, false for even
2757 $x->is_even(); # true if even, false for odd
2758 $x->is_int(); # true if $x is an integer
2760 The return true when the argument satisfies the condition. C<NaN>, C<+inf>,
2761 C<-inf> are not integers and are neither odd nor even.
2767 Compares $x with $y and takes the sign into account.
2768 Returns -1, 0, 1 or undef.
2774 Compares $x with $y while ignoring their. Returns -1, 0, 1 or undef.
2780 Return the sign, of $x, meaning either C<+>, C<->, C<-inf>, C<+inf> or NaN.
2784 $x->digit($n); # return the nth digit, counting from right
2790 Negate the number, e.g. change the sign between '+' and '-', or between '+inf'
2791 and '-inf', respectively. Does nothing for NaN or zero.
2797 Set the number to it's absolute value, e.g. change the sign from '-' to '+'
2798 and from '-inf' to '+inf', respectively. Does nothing for NaN or positive
2803 $x->bnorm(); # normalize (no-op)
2807 $x->bnot(); # two's complement (bit wise not)
2811 $x->binc(); # increment x by 1
2815 $x->bdec(); # decrement x by 1
2819 $x->badd($y); # addition (add $y to $x)
2823 $x->bsub($y); # subtraction (subtract $y from $x)
2827 $x->bmul($y); # multiplication (multiply $x by $y)
2831 $x->bdiv($y); # divide, set $x to quotient
2832 # return (quo,rem) or quo if scalar
2836 $x->bmod($y); # modulus (x % y)
2840 $x->bpow($y); # power of arguments (x ** y)
2844 $x->blsft($y); # left shift
2845 $x->blsft($y,$n); # left shift, by base $n (like 10)
2849 $x->brsft($y); # right shift
2850 $x->brsft($y,$n); # right shift, by base $n (like 10)
2854 $x->band($y); # bitwise and
2858 $x->bior($y); # bitwise inclusive or
2862 $x->bxor($y); # bitwise exclusive or
2866 $x->bnot(); # bitwise not (two's complement)
2870 $x->bsqrt(); # calculate square-root
2874 $x->bfac(); # factorial of $x (1*2*3*4*..$x)
2878 $x->round($A,$P,$round_mode); # round to accuracy or precision using mode $r
2882 $x->bround($N); # accuracy: preserve $N digits
2886 $x->bfround($N); # round to $Nth digit, no-op for BigInts
2892 Set $x to the integer less or equal than $x. This is a no-op in BigInt, but
2893 does change $x in BigFloat.
2899 Set $x to the integer greater or equal than $x. This is a no-op in BigInt, but
2900 does change $x in BigFloat.
2904 bgcd(@values); # greatest common divisor (no OO style)
2908 blcm(@values); # lowest common multiplicator (no OO style)
2913 ($xl,$fl) = $x->length();
2915 Returns the number of digits in the decimal representation of the number.
2916 In list context, returns the length of the integer and fraction part. For
2917 BigInt's, the length of the fraction part will always be 0.
2923 Return the exponent of $x as BigInt.
2929 Return the signed mantissa of $x as BigInt.
2933 $x->parts(); # return (mantissa,exponent) as BigInt
2937 $x->copy(); # make a true copy of $x (unlike $y = $x;)
2941 $x->as_number(); # return as BigInt (in BigInt: same as copy())
2945 $x->bstr(); # normalized string
2949 $x->bsstr(); # normalized string in scientific notation
2953 $x->as_hex(); # as signed hexadecimal string with prefixed 0x
2957 $x->as_bin(); # as signed binary string with prefixed 0b
2959 =head1 ACCURACY and PRECISION
2961 Since version v1.33, Math::BigInt and Math::BigFloat have full support for
2962 accuracy and precision based rounding, both automatically after every
2963 operation as well as manually.
2965 This section describes the accuracy/precision handling in Math::Big* as it
2966 used to be and as it is now, complete with an explanation of all terms and
2969 Not yet implemented things (but with correct description) are marked with '!',
2970 things that need to be answered are marked with '?'.
2972 In the next paragraph follows a short description of terms used here (because
2973 these may differ from terms used by others people or documentation).
2975 During the rest of this document, the shortcuts A (for accuracy), P (for
2976 precision), F (fallback) and R (rounding mode) will be used.
2980 A fixed number of digits before (positive) or after (negative)
2981 the decimal point. For example, 123.45 has a precision of -2. 0 means an
2982 integer like 123 (or 120). A precision of 2 means two digits to the left
2983 of the decimal point are zero, so 123 with P = 1 becomes 120. Note that
2984 numbers with zeros before the decimal point may have different precisions,
2985 because 1200 can have p = 0, 1 or 2 (depending on what the inital value
2986 was). It could also have p < 0, when the digits after the decimal point
2989 The string output (of floating point numbers) will be padded with zeros:
2991 Initial value P A Result String
2992 ------------------------------------------------------------
2993 1234.01 -3 1000 1000
2996 1234.001 1 1234 1234.0
2998 1234.01 2 1234.01 1234.01
2999 1234.01 5 1234.01 1234.01000
3001 For BigInts, no padding occurs.
3005 Number of significant digits. Leading zeros are not counted. A
3006 number may have an accuracy greater than the non-zero digits
3007 when there are zeros in it or trailing zeros. For example, 123.456 has
3008 A of 6, 10203 has 5, 123.0506 has 7, 123.450000 has 8 and 0.000123 has 3.
3010 The string output (of floating point numbers) will be padded with zeros:
3012 Initial value P A Result String
3013 ------------------------------------------------------------
3015 1234.01 6 1234.01 1234.01
3016 1234.1 8 1234.1 1234.1000
3018 For BigInts, no padding occurs.
3022 When both A and P are undefined, this is used as a fallback accuracy when
3025 =head2 Rounding mode R
3027 When rounding a number, different 'styles' or 'kinds'
3028 of rounding are possible. (Note that random rounding, as in
3029 Math::Round, is not implemented.)
3035 truncation invariably removes all digits following the
3036 rounding place, replacing them with zeros. Thus, 987.65 rounded
3037 to tens (P=1) becomes 980, and rounded to the fourth sigdig
3038 becomes 987.6 (A=4). 123.456 rounded to the second place after the
3039 decimal point (P=-2) becomes 123.46.
3041 All other implemented styles of rounding attempt to round to the
3042 "nearest digit." If the digit D immediately to the right of the
3043 rounding place (skipping the decimal point) is greater than 5, the
3044 number is incremented at the rounding place (possibly causing a
3045 cascade of incrementation): e.g. when rounding to units, 0.9 rounds
3046 to 1, and -19.9 rounds to -20. If D < 5, the number is similarly
3047 truncated at the rounding place: e.g. when rounding to units, 0.4
3048 rounds to 0, and -19.4 rounds to -19.
3050 However the results of other styles of rounding differ if the
3051 digit immediately to the right of the rounding place (skipping the
3052 decimal point) is 5 and if there are no digits, or no digits other
3053 than 0, after that 5. In such cases:
3057 rounds the digit at the rounding place to 0, 2, 4, 6, or 8
3058 if it is not already. E.g., when rounding to the first sigdig, 0.45
3059 becomes 0.4, -0.55 becomes -0.6, but 0.4501 becomes 0.5.
3063 rounds the digit at the rounding place to 1, 3, 5, 7, or 9 if
3064 it is not already. E.g., when rounding to the first sigdig, 0.45
3065 becomes 0.5, -0.55 becomes -0.5, but 0.5501 becomes 0.6.
3069 round to plus infinity, i.e. always round up. E.g., when
3070 rounding to the first sigdig, 0.45 becomes 0.5, -0.55 becomes -0.5,
3071 and 0.4501 also becomes 0.5.
3075 round to minus infinity, i.e. always round down. E.g., when
3076 rounding to the first sigdig, 0.45 becomes 0.4, -0.55 becomes -0.6,
3077 but 0.4501 becomes 0.5.
3081 round to zero, i.e. positive numbers down, negative ones up.
3082 E.g., when rounding to the first sigdig, 0.45 becomes 0.4, -0.55
3083 becomes -0.5, but 0.4501 becomes 0.5.
3087 The handling of A & P in MBI/MBF (the old core code shipped with Perl
3088 versions <= 5.7.2) is like this:
3094 * ffround($p) is able to round to $p number of digits after the decimal
3096 * otherwise P is unused
3098 =item Accuracy (significant digits)
3100 * fround($a) rounds to $a significant digits
3101 * only fdiv() and fsqrt() take A as (optional) paramater
3102 + other operations simply create the same number (fneg etc), or more (fmul)
3104 + rounding/truncating is only done when explicitly calling one of fround
3105 or ffround, and never for BigInt (not implemented)
3106 * fsqrt() simply hands its accuracy argument over to fdiv.
3107 * the documentation and the comment in the code indicate two different ways
3108 on how fdiv() determines the maximum number of digits it should calculate,
3109 and the actual code does yet another thing
3111 max($Math::BigFloat::div_scale,length(dividend)+length(divisor))
3113 result has at most max(scale, length(dividend), length(divisor)) digits
3115 scale = max(scale, length(dividend)-1,length(divisor)-1);
3116 scale += length(divisior) - length(dividend);
3117 So for lx = 3, ly = 9, scale = 10, scale will actually be 16 (10+9-3).
3118 Actually, the 'difference' added to the scale is calculated from the
3119 number of "significant digits" in dividend and divisor, which is derived
3120 by looking at the length of the mantissa. Which is wrong, since it includes
3121 the + sign (oups) and actually gets 2 for '+100' and 4 for '+101'. Oups
3122 again. Thus 124/3 with div_scale=1 will get you '41.3' based on the strange
3123 assumption that 124 has 3 significant digits, while 120/7 will get you
3124 '17', not '17.1' since 120 is thought to have 2 significant digits.
3125 The rounding after the division then uses the remainder and $y to determine
3126 wether it must round up or down.
3127 ? I have no idea which is the right way. That's why I used a slightly more
3128 ? simple scheme and tweaked the few failing testcases to match it.
3132 This is how it works now:
3136 =item Setting/Accessing
3138 * You can set the A global via Math::BigInt->accuracy() or
3139 Math::BigFloat->accuracy() or whatever class you are using.
3140 * You can also set P globally by using Math::SomeClass->precision() likewise.
3141 * Globals are classwide, and not inherited by subclasses.
3142 * to undefine A, use Math::SomeCLass->accuracy(undef);
3143 * to undefine P, use Math::SomeClass->precision(undef);
3144 * Setting Math::SomeClass->accuracy() clears automatically
3145 Math::SomeClass->precision(), and vice versa.
3146 * To be valid, A must be > 0, P can have any value.
3147 * If P is negative, this means round to the P'th place to the right of the
3148 decimal point; positive values mean to the left of the decimal point.
3149 P of 0 means round to integer.
3150 * to find out the current global A, take Math::SomeClass->accuracy()
3151 * to find out the current global P, take Math::SomeClass->precision()
3152 * use $x->accuracy() respective $x->precision() for the local setting of $x.
3153 * Please note that $x->accuracy() respecive $x->precision() fall back to the
3154 defined globals, when $x's A or P is not set.
3156 =item Creating numbers
3158 * When you create a number, you can give it's desired A or P via:
3159 $x = Math::BigInt->new($number,$A,$P);
3160 * Only one of A or P can be defined, otherwise the result is NaN
3161 * If no A or P is give ($x = Math::BigInt->new($number) form), then the
3162 globals (if set) will be used. Thus changing the global defaults later on
3163 will not change the A or P of previously created numbers (i.e., A and P of
3164 $x will be what was in effect when $x was created)
3165 * If given undef for A and P, B<no> rounding will occur, and the globals will
3166 B<not> be used. This is used by subclasses to create numbers without
3167 suffering rounding in the parent. Thus a subclass is able to have it's own
3168 globals enforced upon creation of a number by using
3169 $x = Math::BigInt->new($number,undef,undef):
3171 use Math::Bigint::SomeSubclass;
3174 Math::BigInt->accuracy(2);
3175 Math::BigInt::SomeSubClass->accuracy(3);
3176 $x = Math::BigInt::SomeSubClass->new(1234);
3178 $x is now 1230, and not 1200. A subclass might choose to implement
3179 this otherwise, e.g. falling back to the parent's A and P.
3183 * If A or P are enabled/defined, they are used to round the result of each
3184 operation according to the rules below
3185 * Negative P is ignored in Math::BigInt, since BigInts never have digits
3186 after the decimal point
3187 * Math::BigFloat uses Math::BigInts internally, but setting A or P inside
3188 Math::BigInt as globals should not tamper with the parts of a BigFloat.
3189 Thus a flag is used to mark all Math::BigFloat numbers as 'never round'
3193 * It only makes sense that a number has only one of A or P at a time.
3194 Since you can set/get both A and P, there is a rule that will practically
3195 enforce only A or P to be in effect at a time, even if both are set.
3196 This is called precedence.
3197 * If two objects are involved in an operation, and one of them has A in
3198 effect, and the other P, this results in an error (NaN).
3199 * A takes precendence over P (Hint: A comes before P). If A is defined, it
3200 is used, otherwise P is used. If neither of them is defined, nothing is
3201 used, i.e. the result will have as many digits as it can (with an
3202 exception for fdiv/fsqrt) and will not be rounded.
3203 * There is another setting for fdiv() (and thus for fsqrt()). If neither of
3204 A or P is defined, fdiv() will use a fallback (F) of $div_scale digits.
3205 If either the dividend's or the divisor's mantissa has more digits than
3206 the value of F, the higher value will be used instead of F.
3207 This is to limit the digits (A) of the result (just consider what would
3208 happen with unlimited A and P in the case of 1/3 :-)
3209 * fdiv will calculate (at least) 4 more digits than required (determined by
3210 A, P or F), and, if F is not used, round the result
3211 (this will still fail in the case of a result like 0.12345000000001 with A
3212 or P of 5, but this can not be helped - or can it?)
3213 * Thus you can have the math done by on Math::Big* class in three modes:
3214 + never round (this is the default):
3215 This is done by setting A and P to undef. No math operation
3216 will round the result, with fdiv() and fsqrt() as exceptions to guard
3217 against overflows. You must explicitely call bround(), bfround() or
3218 round() (the latter with parameters).
3219 Note: Once you have rounded a number, the settings will 'stick' on it
3220 and 'infect' all other numbers engaged in math operations with it, since
3221 local settings have the highest precedence. So, to get SaferRound[tm],
3222 use a copy() before rounding like this:
3224 $x = Math::BigFloat->new(12.34);
3225 $y = Math::BigFloat->new(98.76);
3226 $z = $x * $y; # 1218.6984
3227 print $x->copy()->fround(3); # 12.3 (but A is now 3!)
3228 $z = $x * $y; # still 1218.6984, without
3229 # copy would have been 1210!
3231 + round after each op:
3232 After each single operation (except for testing like is_zero()), the
3233 method round() is called and the result is rounded appropriately. By
3234 setting proper values for A and P, you can have all-the-same-A or
3235 all-the-same-P modes. For example, Math::Currency might set A to undef,
3236 and P to -2, globally.
3238 ?Maybe an extra option that forbids local A & P settings would be in order,
3239 ?so that intermediate rounding does not 'poison' further math?
3241 =item Overriding globals
3243 * you will be able to give A, P and R as an argument to all the calculation
3244 routines; the second parameter is A, the third one is P, and the fourth is
3245 R (shift right by one for binary operations like badd). P is used only if
3246 the first parameter (A) is undefined. These three parameters override the
3247 globals in the order detailed as follows, i.e. the first defined value
3249 (local: per object, global: global default, parameter: argument to sub)
3252 + local A (if defined on both of the operands: smaller one is taken)
3253 + local P (if defined on both of the operands: bigger one is taken)
3257 * fsqrt() will hand its arguments to fdiv(), as it used to, only now for two
3258 arguments (A and P) instead of one
3260 =item Local settings
3262 * You can set A and P locally by using $x->accuracy() and $x->precision()
3263 and thus force different A and P for different objects/numbers.
3264 * Setting A or P this way immediately rounds $x to the new value.
3265 * $x->accuracy() clears $x->precision(), and vice versa.
3269 * the rounding routines will use the respective global or local settings.
3270 fround()/bround() is for accuracy rounding, while ffround()/bfround()
3272 * the two rounding functions take as the second parameter one of the
3273 following rounding modes (R):
3274 'even', 'odd', '+inf', '-inf', 'zero', 'trunc'
3275 * you can set and get the global R by using Math::SomeClass->round_mode()
3276 or by setting $Math::SomeClass::round_mode
3277 * after each operation, $result->round() is called, and the result may
3278 eventually be rounded (that is, if A or P were set either locally,
3279 globally or as parameter to the operation)
3280 * to manually round a number, call $x->round($A,$P,$round_mode);
3281 this will round the number by using the appropriate rounding function
3282 and then normalize it.
3283 * rounding modifies the local settings of the number:
3285 $x = Math::BigFloat->new(123.456);
3289 Here 4 takes precedence over 5, so 123.5 is the result and $x->accuracy()
3290 will be 4 from now on.
3292 =item Default values
3301 * The defaults are set up so that the new code gives the same results as
3302 the old code (except in a few cases on fdiv):
3303 + Both A and P are undefined and thus will not be used for rounding
3304 after each operation.
3305 + round() is thus a no-op, unless given extra parameters A and P
3311 The actual numbers are stored as unsigned big integers (with seperate sign).
3312 You should neither care about nor depend on the internal representation; it
3313 might change without notice. Use only method calls like C<< $x->sign(); >>
3314 instead relying on the internal hash keys like in C<< $x->{sign}; >>.
3318 Math with the numbers is done (by default) by a module called
3319 Math::BigInt::Calc. This is equivalent to saying:
3321 use Math::BigInt lib => 'Calc';
3323 You can change this by using:
3325 use Math::BigInt lib => 'BitVect';
3327 The following would first try to find Math::BigInt::Foo, then
3328 Math::BigInt::Bar, and when this also fails, revert to Math::BigInt::Calc:
3330 use Math::BigInt lib => 'Foo,Math::BigInt::Bar';
3332 Calc.pm uses as internal format an array of elements of some decimal base
3333 (usually 1e5 or 1e7) with the least significant digit first, while BitVect.pm
3334 uses a bit vector of base 2, most significant bit first. Other modules might
3335 use even different means of representing the numbers. See the respective
3336 module documentation for further details.
3340 The sign is either '+', '-', 'NaN', '+inf' or '-inf' and stored seperately.
3342 A sign of 'NaN' is used to represent the result when input arguments are not
3343 numbers or as a result of 0/0. '+inf' and '-inf' represent plus respectively
3344 minus infinity. You will get '+inf' when dividing a positive number by 0, and
3345 '-inf' when dividing any negative number by 0.
3347 =head2 mantissa(), exponent() and parts()
3349 C<mantissa()> and C<exponent()> return the said parts of the BigInt such
3352 $m = $x->mantissa();
3353 $e = $x->exponent();
3354 $y = $m * ( 10 ** $e );
3355 print "ok\n" if $x == $y;
3357 C<< ($m,$e) = $x->parts() >> is just a shortcut that gives you both of them
3358 in one go. Both the returned mantissa and exponent have a sign.
3360 Currently, for BigInts C<$e> will be always 0, except for NaN, +inf and -inf,
3361 where it will be NaN; and for $x == 0, where it will be 1
3362 (to be compatible with Math::BigFloat's internal representation of a zero as
3365 C<$m> will always be a copy of the original number. The relation between $e
3366 and $m might change in the future, but will always be equivalent in a
3367 numerical sense, e.g. $m might get minimized.
3373 sub bint { Math::BigInt->new(shift); }
3375 $x = Math::BigInt->bstr("1234") # string "1234"
3376 $x = "$x"; # same as bstr()
3377 $x = Math::BigInt->bneg("1234"); # Bigint "-1234"
3378 $x = Math::BigInt->babs("-12345"); # Bigint "12345"
3379 $x = Math::BigInt->bnorm("-0 00"); # BigInt "0"
3380 $x = bint(1) + bint(2); # BigInt "3"
3381 $x = bint(1) + "2"; # ditto (auto-BigIntify of "2")
3382 $x = bint(1); # BigInt "1"
3383 $x = $x + 5 / 2; # BigInt "3"
3384 $x = $x ** 3; # BigInt "27"
3385 $x *= 2; # BigInt "54"
3386 $x = Math::BigInt->new(0); # BigInt "0"
3388 $x = Math::BigInt->badd(4,5) # BigInt "9"
3389 print $x->bsstr(); # 9e+0
3391 Examples for rounding:
3396 $x = Math::BigFloat->new(123.4567);
3397 $y = Math::BigFloat->new(123.456789);
3398 Math::BigFloat->accuracy(4); # no more A than 4
3400 ok ($x->copy()->fround(),123.4); # even rounding
3401 print $x->copy()->fround(),"\n"; # 123.4
3402 Math::BigFloat->round_mode('odd'); # round to odd
3403 print $x->copy()->fround(),"\n"; # 123.5
3404 Math::BigFloat->accuracy(5); # no more A than 5
3405 Math::BigFloat->round_mode('odd'); # round to odd
3406 print $x->copy()->fround(),"\n"; # 123.46
3407 $y = $x->copy()->fround(4),"\n"; # A = 4: 123.4
3408 print "$y, ",$y->accuracy(),"\n"; # 123.4, 4
3410 Math::BigFloat->accuracy(undef); # A not important now
3411 Math::BigFloat->precision(2); # P important
3412 print $x->copy()->bnorm(),"\n"; # 123.46
3413 print $x->copy()->fround(),"\n"; # 123.46
3415 Examples for converting:
3417 my $x = Math::BigInt->new('0b1'.'01' x 123);
3418 print "bin: ",$x->as_bin()," hex:",$x->as_hex()," dec: ",$x,"\n";
3420 =head1 Autocreating constants
3422 After C<use Math::BigInt ':constant'> all the B<integer> decimal, hexadecimal
3423 and binary constants in the given scope are converted to C<Math::BigInt>.
3424 This conversion happens at compile time.
3428 perl -MMath::BigInt=:constant -e 'print 2**100,"\n"'
3430 prints the integer value of C<2**100>. Note that without conversion of
3431 constants the expression 2**100 will be calculated as perl scalar.
3433 Please note that strings and floating point constants are not affected,
3436 use Math::BigInt qw/:constant/;
3438 $x = 1234567890123456789012345678901234567890
3439 + 123456789123456789;
3440 $y = '1234567890123456789012345678901234567890'
3441 + '123456789123456789';
3443 do not work. You need an explicit Math::BigInt->new() around one of the
3444 operands. You should also quote large constants to protect loss of precision:
3448 $x = Math::BigInt->new('1234567889123456789123456789123456789');
3450 Without the quotes Perl would convert the large number to a floating point
3451 constant at compile time and then hand the result to BigInt, which results in
3452 an truncated result or a NaN.
3454 This also applies to integers that look like floating point constants:
3456 use Math::BigInt ':constant';
3458 print ref(123e2),"\n";
3459 print ref(123.2e2),"\n";
3461 will print nothing but newlines. Use either L<bignum> or L<Math::BigFloat>
3462 to get this to work.
3466 Using the form $x += $y; etc over $x = $x + $y is faster, since a copy of $x
3467 must be made in the second case. For long numbers, the copy can eat up to 20%
3468 of the work (in the case of addition/subtraction, less for
3469 multiplication/division). If $y is very small compared to $x, the form
3470 $x += $y is MUCH faster than $x = $x + $y since making the copy of $x takes
3471 more time then the actual addition.
3473 With a technique called copy-on-write, the cost of copying with overload could
3474 be minimized or even completely avoided. A test implementation of COW did show
3475 performance gains for overloaded math, but introduced a performance loss due
3476 to a constant overhead for all other operatons.
3478 The rewritten version of this module is slower on certain operations, like
3479 new(), bstr() and numify(). The reason are that it does now more work and
3480 handles more cases. The time spent in these operations is usually gained in
3481 the other operations so that programs on the average should get faster. If
3482 they don't, please contect the author.
3484 Some operations may be slower for small numbers, but are significantly faster
3485 for big numbers. Other operations are now constant (O(1), like bneg(), babs()
3486 etc), instead of O(N) and thus nearly always take much less time. These
3487 optimizations were done on purpose.
3489 If you find the Calc module to slow, try to install any of the replacement
3490 modules and see if they help you.
3492 =head2 Alternative math libraries
3494 You can use an alternative library to drive Math::BigInt via:
3496 use Math::BigInt lib => 'Module';
3498 See L<MATH LIBRARY> for more information.
3500 For more benchmark results see L<http://bloodgate.com/perl/benchmarks.html>.
3504 =head1 Subclassing Math::BigInt
3506 The basic design of Math::BigInt allows simple subclasses with very little
3507 work, as long as a few simple rules are followed:
3513 The public API must remain consistent, i.e. if a sub-class is overloading
3514 addition, the sub-class must use the same name, in this case badd(). The
3515 reason for this is that Math::BigInt is optimized to call the object methods
3520 The private object hash keys like C<$x->{sign}> may not be changed, but
3521 additional keys can be added, like C<$x->{_custom}>.
3525 Accessor functions are available for all existing object hash keys and should
3526 be used instead of directly accessing the internal hash keys. The reason for
3527 this is that Math::BigInt itself has a pluggable interface which permits it
3528 to support different storage methods.
3532 More complex sub-classes may have to replicate more of the logic internal of
3533 Math::BigInt if they need to change more basic behaviors. A subclass that
3534 needs to merely change the output only needs to overload C<bstr()>.
3536 All other object methods and overloaded functions can be directly inherited
3537 from the parent class.
3539 At the very minimum, any subclass will need to provide it's own C<new()> and can
3540 store additional hash keys in the object. There are also some package globals
3541 that must be defined, e.g.:
3545 $precision = -2; # round to 2 decimal places
3546 $round_mode = 'even';
3549 Additionally, you might want to provide the following two globals to allow
3550 auto-upgrading and auto-downgrading to work correctly:
3555 This allows Math::BigInt to correctly retrieve package globals from the
3556 subclass, like C<$SubClass::precision>. See t/Math/BigInt/Subclass.pm or
3557 t/Math/BigFloat/SubClass.pm completely functional subclass examples.
3563 in your subclass to automatically inherit the overloading from the parent. If
3564 you like, you can change part of the overloading, look at Math::String for an
3569 When used like this:
3571 use Math::BigInt upgrade => 'Foo::Bar';
3573 certain operations will 'upgrade' their calculation and thus the result to
3574 the class Foo::Bar. Usually this is used in conjunction with Math::BigFloat:
3576 use Math::BigInt upgrade => 'Math::BigFloat';
3578 As a shortcut, you can use the module C<bignum>:
3582 Also good for oneliners:
3584 perl -Mbignum -le 'print 2 ** 255'
3586 This makes it possible to mix arguments of different classes (as in 2.5 + 2)
3587 as well es preserve accuracy (as in sqrt(3)).
3589 Beware: This feature is not fully implemented yet.
3593 The following methods upgrade themselves unconditionally; that is if upgrade
3594 is in effect, they will always hand up their work:
3606 Beware: This list is not complete.
3608 All other methods upgrade themselves only when one (or all) of their
3609 arguments are of the class mentioned in $upgrade (This might change in later
3610 versions to a more sophisticated scheme):
3616 =item Out of Memory!
3618 Under Perl prior to 5.6.0 having an C<use Math::BigInt ':constant';> and
3619 C<eval()> in your code will crash with "Out of memory". This is probably an
3620 overload/exporter bug. You can workaround by not having C<eval()>
3621 and ':constant' at the same time or upgrade your Perl to a newer version.
3623 =item Fails to load Calc on Perl prior 5.6.0
3625 Since eval(' use ...') can not be used in conjunction with ':constant', BigInt
3626 will fall back to eval { require ... } when loading the math lib on Perls
3627 prior to 5.6.0. This simple replaces '::' with '/' and thus might fail on
3628 filesystems using a different seperator.
3634 Some things might not work as you expect them. Below is documented what is
3635 known to be troublesome:
3639 =item stringify, bstr(), bsstr() and 'cmp'
3641 Both stringify and bstr() now drop the leading '+'. The old code would return
3642 '+3', the new returns '3'. This is to be consistent with Perl and to make
3643 cmp (especially with overloading) to work as you expect. It also solves
3644 problems with Test.pm, it's ok() uses 'eq' internally.
3646 Mark said, when asked about to drop the '+' altogether, or make only cmp work:
3648 I agree (with the first alternative), don't add the '+' on positive
3649 numbers. It's not as important anymore with the new internal
3650 form for numbers. It made doing things like abs and neg easier,
3651 but those have to be done differently now anyway.
3653 So, the following examples will now work all as expected:
3656 BEGIN { plan tests => 1 }
3659 my $x = new Math::BigInt 3*3;
3660 my $y = new Math::BigInt 3*3;
3663 print "$x eq 9" if $x eq $y;
3664 print "$x eq 9" if $x eq '9';
3665 print "$x eq 9" if $x eq 3*3;
3667 Additionally, the following still works:
3669 print "$x == 9" if $x == $y;
3670 print "$x == 9" if $x == 9;
3671 print "$x == 9" if $x == 3*3;
3673 There is now a C<bsstr()> method to get the string in scientific notation aka
3674 C<1e+2> instead of C<100>. Be advised that overloaded 'eq' always uses bstr()
3675 for comparisation, but Perl will represent some numbers as 100 and others
3676 as 1e+308. If in doubt, convert both arguments to Math::BigInt before doing eq:
3679 BEGIN { plan tests => 3 }
3682 $x = Math::BigInt->new('1e56'); $y = 1e56;
3683 ok ($x,$y); # will fail
3684 ok ($x->bsstr(),$y); # okay
3685 $y = Math::BigInt->new($y);
3688 Alternatively, simple use <=> for comparisations, that will get it always
3689 right. There is not yet a way to get a number automatically represented as
3690 a string that matches exactly the way Perl represents it.
3694 C<int()> will return (at least for Perl v5.7.1 and up) another BigInt, not a
3697 $x = Math::BigInt->new(123);
3698 $y = int($x); # BigInt 123
3699 $x = Math::BigFloat->new(123.45);
3700 $y = int($x); # BigInt 123
3702 In all Perl versions you can use C<as_number()> for the same effect:
3704 $x = Math::BigFloat->new(123.45);
3705 $y = $x->as_number(); # BigInt 123
3707 This also works for other subclasses, like Math::String.
3709 It is yet unlcear whether overloaded int() should return a scalar or a BigInt.
3713 The following will probably not do what you expect:
3715 $c = Math::BigInt->new(123);
3716 print $c->length(),"\n"; # prints 30
3718 It prints both the number of digits in the number and in the fraction part
3719 since print calls C<length()> in list context. Use something like:
3721 print scalar $c->length(),"\n"; # prints 3
3725 The following will probably not do what you expect:
3727 print $c->bdiv(10000),"\n";
3729 It prints both quotient and remainder since print calls C<bdiv()> in list
3730 context. Also, C<bdiv()> will modify $c, so be carefull. You probably want
3733 print $c / 10000,"\n";
3734 print scalar $c->bdiv(10000),"\n"; # or if you want to modify $c
3738 The quotient is always the greatest integer less than or equal to the
3739 real-valued quotient of the two operands, and the remainder (when it is
3740 nonzero) always has the same sign as the second operand; so, for
3750 As a consequence, the behavior of the operator % agrees with the
3751 behavior of Perl's built-in % operator (as documented in the perlop
3752 manpage), and the equation
3754 $x == ($x / $y) * $y + ($x % $y)
3756 holds true for any $x and $y, which justifies calling the two return
3757 values of bdiv() the quotient and remainder. The only exception to this rule
3758 are when $y == 0 and $x is negative, then the remainder will also be
3759 negative. See below under "infinity handling" for the reasoning behing this.
3761 Perl's 'use integer;' changes the behaviour of % and / for scalars, but will
3762 not change BigInt's way to do things. This is because under 'use integer' Perl
3763 will do what the underlying C thinks is right and this is different for each
3764 system. If you need BigInt's behaving exactly like Perl's 'use integer', bug
3765 the author to implement it ;)
3767 =item infinity handling
3769 Here are some examples that explain the reasons why certain results occur while
3772 The following table shows the result of the division and the remainder, so that
3773 the equation above holds true. Some "ordinary" cases are strewn in to show more
3774 clearly the reasoning:
3776 A / B = C, R so that C * B + R = A
3777 =========================================================
3778 5 / 8 = 0, 5 0 * 8 + 5 = 5
3779 0 / 8 = 0, 0 0 * 8 + 0 = 0
3780 0 / inf = 0, 0 0 * inf + 0 = 0
3781 0 /-inf = 0, 0 0 * -inf + 0 = 0
3782 5 / inf = 0, 5 0 * inf + 5 = 5
3783 5 /-inf = 0, 5 0 * -inf + 5 = 5
3784 -5/ inf = 0, -5 0 * inf + -5 = -5
3785 -5/-inf = 0, -5 0 * -inf + -5 = -5
3786 inf/ 5 = inf, 0 inf * 5 + 0 = inf
3787 -inf/ 5 = -inf, 0 -inf * 5 + 0 = -inf
3788 inf/ -5 = -inf, 0 -inf * -5 + 0 = inf
3789 -inf/ -5 = inf, 0 inf * -5 + 0 = -inf
3790 5/ 5 = 1, 0 1 * 5 + 0 = 5
3791 -5/ -5 = 1, 0 1 * -5 + 0 = -5
3792 inf/ inf = 1, 0 1 * inf + 0 = inf
3793 -inf/-inf = 1, 0 1 * -inf + 0 = -inf
3794 inf/-inf = -1, 0 -1 * -inf + 0 = inf
3795 -inf/ inf = -1, 0 1 * -inf + 0 = -inf
3796 8/ 0 = inf, 8 inf * 0 + 8 = 8
3797 inf/ 0 = inf, inf inf * 0 + inf = inf
3800 These cases below violate the "remainder has the sign of the second of the two
3801 arguments", since they wouldn't match up otherwise.
3803 A / B = C, R so that C * B + R = A
3804 ========================================================
3805 -inf/ 0 = -inf, -inf -inf * 0 + inf = -inf
3806 -8/ 0 = -inf, -8 -inf * 0 + 8 = -8
3808 =item Modifying and =
3812 $x = Math::BigFloat->new(5);
3815 It will not do what you think, e.g. making a copy of $x. Instead it just makes
3816 a second reference to the B<same> object and stores it in $y. Thus anything
3817 that modifies $x (except overloaded operators) will modify $y, and vice versa.
3818 Or in other words, C<=> is only safe if you modify your BigInts only via
3819 overloaded math. As soon as you use a method call it breaks:
3822 print "$x, $y\n"; # prints '10, 10'
3824 If you want a true copy of $x, use:
3828 You can also chain the calls like this, this will make first a copy and then
3831 $y = $x->copy()->bmul(2);
3833 See also the documentation for overload.pm regarding C<=>.
3837 C<bpow()> (and the rounding functions) now modifies the first argument and
3838 returns it, unlike the old code which left it alone and only returned the
3839 result. This is to be consistent with C<badd()> etc. The first three will
3840 modify $x, the last one won't:
3842 print bpow($x,$i),"\n"; # modify $x
3843 print $x->bpow($i),"\n"; # ditto
3844 print $x **= $i,"\n"; # the same
3845 print $x ** $i,"\n"; # leave $x alone
3847 The form C<$x **= $y> is faster than C<$x = $x ** $y;>, though.
3849 =item Overloading -$x
3859 since overload calls C<sub($x,0,1);> instead of C<neg($x)>. The first variant
3860 needs to preserve $x since it does not know that it later will get overwritten.
3861 This makes a copy of $x and takes O(N), but $x->bneg() is O(1).
3863 With Copy-On-Write, this issue would be gone, but C-o-W is not implemented
3864 since it is slower for all other things.
3866 =item Mixing different object types
3868 In Perl you will get a floating point value if you do one of the following:
3874 With overloaded math, only the first two variants will result in a BigFloat:
3879 $mbf = Math::BigFloat->new(5);
3880 $mbi2 = Math::BigInteger->new(5);
3881 $mbi = Math::BigInteger->new(2);
3883 # what actually gets called:
3884 $float = $mbf + $mbi; # $mbf->badd()
3885 $float = $mbf / $mbi; # $mbf->bdiv()
3886 $integer = $mbi + $mbf; # $mbi->badd()
3887 $integer = $mbi2 / $mbi; # $mbi2->bdiv()
3888 $integer = $mbi2 / $mbf; # $mbi2->bdiv()
3890 This is because math with overloaded operators follows the first (dominating)
3891 operand, and the operation of that is called and returns thus the result. So,
3892 Math::BigInt::bdiv() will always return a Math::BigInt, regardless whether
3893 the result should be a Math::BigFloat or the second operant is one.
3895 To get a Math::BigFloat you either need to call the operation manually,
3896 make sure the operands are already of the proper type or casted to that type
3897 via Math::BigFloat->new():
3899 $float = Math::BigFloat->new($mbi2) / $mbi; # = 2.5
3901 Beware of simple "casting" the entire expression, this would only convert
3902 the already computed result:
3904 $float = Math::BigFloat->new($mbi2 / $mbi); # = 2.0 thus wrong!
3906 Beware also of the order of more complicated expressions like:
3908 $integer = ($mbi2 + $mbi) / $mbf; # int / float => int
3909 $integer = $mbi2 / Math::BigFloat->new($mbi); # ditto
3911 If in doubt, break the expression into simpler terms, or cast all operands
3912 to the desired resulting type.
3914 Scalar values are a bit different, since:
3919 will both result in the proper type due to the way the overloaded math works.
3921 This section also applies to other overloaded math packages, like Math::String.
3923 One solution to you problem might be L<autoupgrading|upgrading>.
3927 C<bsqrt()> works only good if the result is a big integer, e.g. the square
3928 root of 144 is 12, but from 12 the square root is 3, regardless of rounding
3931 If you want a better approximation of the square root, then use:
3933 $x = Math::BigFloat->new(12);
3934 Math::BigFloat->precision(0);
3935 Math::BigFloat->round_mode('even');
3936 print $x->copy->bsqrt(),"\n"; # 4
3938 Math::BigFloat->precision(2);
3939 print $x->bsqrt(),"\n"; # 3.46
3940 print $x->bsqrt(3),"\n"; # 3.464
3944 For negative numbers in base see also L<brsft|brsft>.
3950 This program is free software; you may redistribute it and/or modify it under
3951 the same terms as Perl itself.
3955 L<Math::BigFloat> and L<Math::Big> as well as L<Math::BigInt::BitVect>,
3956 L<Math::BigInt::Pari> and L<Math::BigInt::GMP>.
3959 L<http://search.cpan.org/search?mode=module&query=Math%3A%3ABigInt> contains
3960 more documentation including a full version history, testcases, empty
3961 subclass files and benchmarks.
3965 Original code by Mark Biggar, overloaded interface by Ilya Zakharevich.
3966 Completely rewritten by Tels http://bloodgate.com in late 2000, 2001.