3 # Qs: what exactly happens on numify of HUGE numbers? overflow?
4 # $a = -$a is much slower (making copy of $a) than $a->bneg(), hm!?
5 # (copy_on_write will help there, but that is not yet implemented)
7 # The following hash values are used:
8 # value: unsigned int with actual value (as a Math::BigInt::Calc or similiar)
9 # sign : +,-,NaN,+inf,-inf
12 # _f : flags, used by MBF to flag parts of a float as untouchable
13 # _cow : copy on write: number of objects that share the data (NRY)
16 my $class = "Math::BigInt";
21 @ISA = qw( Exporter );
22 @EXPORT_OK = qw( bneg babs bcmp badd bmul bdiv bmod bnorm bsub
25 blsft brsft band bior bxor bnot bpow bnan bzero
26 bacmp bstr bsstr binc bdec bint binf bfloor bceil
27 is_odd is_even is_zero is_one is_nan is_inf sign
28 is_positive is_negative
34 use vars qw/$rnd_mode $accuracy $precision $div_scale/;
37 # Inside overload, the first arg is always an object. If the original code had
38 # it reversed (like $x = 2 * $y), then the third paramater indicates this
39 # swapping. To make it work, we use a helper routine which not only reswaps the
40 # params, but also makes a new object in this case. See _swap() for details,
41 # especially the cases of operators with different classes.
43 # For overloaded ops with only one argument we simple use $_[0]->copy() to
44 # preserve the argument.
46 # Thus inheritance of overload operators becomes possible and transparent for
47 # our subclasses without the need to repeat the entire overload section there.
50 '=' => sub { $_[0]->copy(); },
52 # '+' and '-' do not use _swap, since it is a triffle slower. If you want to
53 # override _swap (if ever), then override overload of '+' and '-', too!
54 # for sub it is a bit tricky to keep b: b-a => -a+b
55 '-' => sub { my $c = $_[0]->copy; $_[2] ?
56 $c->bneg()->badd($_[1]) :
58 '+' => sub { $_[0]->copy()->badd($_[1]); },
60 # some shortcuts for speed (assumes that reversed order of arguments is routed
61 # to normal '+' and we thus can always modify first arg. If this is changed,
62 # this breaks and must be adjusted.)
63 '+=' => sub { $_[0]->badd($_[1]); },
64 '-=' => sub { $_[0]->bsub($_[1]); },
65 '*=' => sub { $_[0]->bmul($_[1]); },
66 '/=' => sub { scalar $_[0]->bdiv($_[1]); },
67 '**=' => sub { $_[0]->bpow($_[1]); },
69 '<=>' => sub { $_[2] ?
70 $class->bcmp($_[1],$_[0]) :
71 $class->bcmp($_[0],$_[1])},
74 $_[1] cmp $_[0]->bstr() :
75 $_[0]->bstr() cmp $_[1] },
77 'int' => sub { $_[0]->copy(); },
78 'neg' => sub { $_[0]->copy()->bneg(); },
79 'abs' => sub { $_[0]->copy()->babs(); },
80 '~' => sub { $_[0]->copy()->bnot(); },
82 '*' => sub { my @a = ref($_[0])->_swap(@_); $a[0]->bmul($a[1]); },
83 '/' => sub { my @a = ref($_[0])->_swap(@_);scalar $a[0]->bdiv($a[1]);},
84 '%' => sub { my @a = ref($_[0])->_swap(@_); $a[0]->bmod($a[1]); },
85 '**' => sub { my @a = ref($_[0])->_swap(@_); $a[0]->bpow($a[1]); },
86 '<<' => sub { my @a = ref($_[0])->_swap(@_); $a[0]->blsft($a[1]); },
87 '>>' => sub { my @a = ref($_[0])->_swap(@_); $a[0]->brsft($a[1]); },
89 '&' => sub { my @a = ref($_[0])->_swap(@_); $a[0]->band($a[1]); },
90 '|' => sub { my @a = ref($_[0])->_swap(@_); $a[0]->bior($a[1]); },
91 '^' => sub { my @a = ref($_[0])->_swap(@_); $a[0]->bxor($a[1]); },
93 # can modify arg of ++ and --, so avoid a new-copy for speed, but don't
94 # use $_[0]->_one(), it modifies $_[0] to be 1!
95 '++' => sub { $_[0]->binc() },
96 '--' => sub { $_[0]->bdec() },
98 # if overloaded, O(1) instead of O(N) and twice as fast for small numbers
100 # this kludge is needed for perl prior 5.6.0 since returning 0 here fails :-/
101 # v5.6.1 dumps on that: return !$_[0]->is_zero() || undef; :-(
102 my $t = !$_[0]->is_zero();
109 0+ numify), # Order of arguments unsignificant
112 ##############################################################################
113 # global constants, flags and accessory
115 use constant MB_NEVER_ROUND => 0x0001;
117 my $NaNOK=1; # are NaNs ok?
118 my $nan = 'NaN'; # constants for easier life
120 my $CALC = 'Math::BigInt::Calc'; # module to do low level math
121 sub _core_lib () { return $CALC; } # for test suite
123 # Rounding modes, one of 'even', 'odd', '+inf', '-inf', 'zero' or 'trunc'
131 # make Class->round_mode() work
132 my $self = shift || $class;
133 # shift @_ if defined $_[0] && $_[0] eq $class;
137 die "Unknown round mode $m"
138 if $m !~ /^(even|odd|\+inf|\-inf|zero|trunc)$/;
139 $rnd_mode = $m; return;
146 # $x->accuracy($a); ref($x) a
147 # $x->accuracy(); ref($x);
148 # Class::accuracy(); # not supported
149 #print "MBI @_ ($class)\n";
152 die ("accuracy() needs reference to object as first parameter.")
158 $x->round() if defined $x->{_a};
167 die ("precision() needs reference to object as first parameter.")
173 $x->round() if defined $x->{_p};
180 # select accuracy parameter based on precedence,
181 # used by bround() and bfround(), may return undef for scale (means no op)
182 my ($x,$s,$m,$scale,$mode) = @_;
183 $scale = $x->{_a} if !defined $scale;
184 $scale = $s if (!defined $scale);
185 $mode = $m if !defined $mode;
186 return ($scale,$mode);
191 # select precision parameter based on precedence,
192 # used by bround() and bfround(), may return undef for scale (means no op)
193 my ($x,$s,$m,$scale,$mode) = @_;
194 $scale = $x->{_p} if !defined $scale;
195 $scale = $s if (!defined $scale);
196 $mode = $m if !defined $mode;
197 return ($scale,$mode);
200 ##############################################################################
208 # if two arguments, the first one is the class to "swallow" subclasses
216 return unless ref($x); # only for objects
218 my $self = {}; bless $self,$c;
219 foreach my $k (keys %$x)
223 $self->{$k} = $CALC->_copy($x->{$k});
225 elsif (ref($x->{$k}) eq 'SCALAR')
227 $self->{$k} = \${$x->{$k}};
229 elsif (ref($x->{$k}) eq 'ARRAY')
231 $self->{$k} = [ @{$x->{$k}} ];
233 elsif (ref($x->{$k}) eq 'HASH')
235 # only one level deep!
236 foreach my $h (keys %{$x->{$k}})
238 $self->{$k}->{$h} = $x->{$k}->{$h};
241 elsif (ref($x->{$k}))
243 my $c = ref($x->{$k});
244 $self->{$k} = $c->new($x->{$k}); # no copy() due to deep rec
248 $self->{$k} = $x->{$k};
256 # create a new BigInt object from a string or another BigInt object.
257 # see hash keys documented at top
259 # the argument could be an object, so avoid ||, && etc on it, this would
260 # cause costly overloaded code to be called. The only allowed ops are
265 my $wanted = shift; # avoid numify call by not using || here
266 return $class->bzero() if !defined $wanted; # default to 0
267 return $class->copy($wanted) if ref($wanted);
269 my $self = {}; bless $self, $class;
270 # handle '+inf', '-inf' first
271 if ($wanted =~ /^[+-]inf$/)
273 $self->{value} = $CALC->_zero();
274 $self->{sign} = $wanted;
277 # split str in m mantissa, e exponent, i integer, f fraction, v value, s sign
278 my ($mis,$miv,$mfv,$es,$ev) = _split(\$wanted);
279 if (ref $mis && !ref $miv)
281 # _from_hex or _from_bin
282 $self->{value} = $mis->{value};
283 $self->{sign} = $mis->{sign};
284 return $self; # throw away $mis
288 die "$wanted is not a number initialized to $class" if !$NaNOK;
290 $self->{value} = $CALC->_zero();
291 $self->{sign} = $nan;
294 # make integer from mantissa by adjusting exp, then convert to bigint
295 $self->{sign} = $$mis; # store sign
296 $self->{value} = $CALC->_zero(); # for all the NaN cases
297 my $e = int("$$es$$ev"); # exponent (avoid recursion)
300 my $diff = $e - CORE::length($$mfv);
301 if ($diff < 0) # Not integer
304 $self->{sign} = $nan;
308 # adjust fraction and add it to value
309 # print "diff > 0 $$miv\n";
310 $$miv = $$miv . ($$mfv . '0' x $diff);
315 if ($$mfv ne '') # e <= 0
317 # fraction and negative/zero E => NOI
318 #print "NOI 2 \$\$mfv '$$mfv'\n";
319 $self->{sign} = $nan;
323 # xE-y, and empty mfv
326 if ($$miv !~ s/0{$e}$//) # can strip so many zero's?
329 $self->{sign} = $nan;
333 $self->{sign} = '+' if $$miv eq '0'; # normalize -0 => +0
334 $self->{value} = $CALC->_new($miv) if $self->{sign} =~ /^[+-]$/;
335 #print "$wanted => $self->{sign}\n";
336 # if any of the globals is set, use them to round and store them inside $self
337 $self->round($accuracy,$precision,$rnd_mode)
338 if defined $accuracy || defined $precision;
342 # some shortcuts for easier life
345 # exportable version of new
346 return $class->new(@_);
351 # create a bigint 'NaN', if given a BigInt, set it to 'NaN'
353 $self = $class if !defined $self;
356 my $c = $self; $self = {}; bless $self, $c;
358 return if $self->modify('bnan');
359 $self->{value} = $CALC->_zero();
360 $self->{sign} = $nan;
366 # create a bigint '+-inf', if given a BigInt, set it to '+-inf'
367 # the sign is either '+', or if given, used from there
369 my $sign = shift; $sign = '+' if !defined $sign || $sign ne '-';
370 $self = $class if !defined $self;
373 my $c = $self; $self = {}; bless $self, $c;
375 return if $self->modify('binf');
376 $self->{value} = $CALC->_zero();
377 $self->{sign} = $sign.'inf';
383 # create a bigint '+0', if given a BigInt, set it to 0
385 $self = $class if !defined $self;
386 #print "bzero $self\n";
390 my $c = $self; $self = {}; bless $self, $c;
392 return if $self->modify('bzero');
393 $self->{value} = $CALC->_zero();
395 #print "result: $self\n";
399 ##############################################################################
400 # string conversation
404 # (ref to BFLOAT or num_str ) return num_str
405 # Convert number from internal format to scientific string format.
406 # internal format is always normalized (no leading zeros, "-0E0" => "+0E0")
407 my ($self,$x) = objectify(1,@_);
409 return $x->{sign} if $x->{sign} !~ /^[+-]$/;
410 my ($m,$e) = $x->parts();
411 # can be only '+', so
413 # MBF: my $s = $e->{sign}; $s = '' if $s eq '-'; my $sep = 'e'.$s;
414 return $m->bstr().$sign.$e->bstr();
419 # make a string from bigint object
420 my $x = shift; $x = $class->new($x) unless ref $x;
421 return $x->{sign} if $x->{sign} !~ /^[+-]$/;
422 my $es = ''; $es = $x->{sign} if $x->{sign} eq '-';
423 return $es.${$CALC->_str($x->{value})};
428 # Make a number from a BigInt object
429 my $x = shift; $x = $class->new($x) unless ref $x;
430 return $x->{sign} if $x->{sign} !~ /^[+-]$/;
431 my $num = $CALC->_num($x->{value});
432 return -$num if $x->{sign} eq '-';
436 ##############################################################################
437 # public stuff (usually prefixed with "b")
441 # return the sign of the number: +/-/NaN
442 my ($self,$x) = objectify(1,@_);
448 # After any operation or when calling round(), the result is rounded by
449 # regarding the A & P from arguments, local parameters, or globals.
450 # The result's A or P are set by the rounding, but not inspected beforehand
451 # (aka only the arguments enter into it). This works because the given
452 # 'first' argument is both the result and true first argument with unchanged
454 # This does not yet handle $x with A, and $y with P (which should be an
457 my $a = shift; # accuracy, if given by caller
458 my $p = shift; # precision, if given by caller
459 my $r = shift; # round_mode, if given by caller
460 my @args = @_; # all 'other' arguments (0 for unary, 1 for binary ops)
462 # leave bigfloat parts alone
463 return $self if exists $self->{_f} && $self->{_f} & MB_NEVER_ROUND != 0;
465 unshift @args,$self; # add 'first' argument
467 $self = new($self) unless ref($self); # if not object, make one
469 # find out class of argument to round
470 my $c = ref($args[0]);
472 # now pick $a or $p, but only if we have got "arguments"
473 if ((!defined $a) && (!defined $p) && (@args > 0))
477 # take the defined one, or if both defined, the one that is smaller
478 $a = $_->{_a} if (defined $_->{_a}) && (!defined $a || $_->{_a} < $a);
480 if (!defined $a) # if it still is not defined, take p
484 # take the defined one, or if both defined, the one that is smaller
485 $p = $_->{_p} if (defined $_->{_p}) && (!defined $p || $_->{_p} < $p);
487 # if none defined, use globals (#2)
491 my $z = "$c\::accuracy"; $a = $$z;
494 $z = "$c\::precision"; $p = $$z;
498 } # endif !$a || !$P && args > 0
499 # for clearity, this is not merged at place (#2)
500 # now round, by calling fround or ffround:
503 $self->{_a} = $a; $self->bround($a,$r);
507 $self->{_p} = $p; $self->bfround($p,$r);
509 return $self->bnorm();
514 # (num_str or BINT) return BINT
515 # Normalize number -- no-op here
523 # (BINT or num_str) return BINT
524 # make number absolute, or return absolute BINT from string
525 #my ($self,$x) = objectify(1,@_);
526 my $x = shift; $x = $class->new($x) unless ref $x;
527 return $x if $x->modify('babs');
528 # post-normalized abs for internal use (does nothing for NaN)
529 $x->{sign} =~ s/^-/+/;
535 # (BINT or num_str) return BINT
536 # negate number or make a negated number from string
537 my ($self,$x,$a,$p,$r) = objectify(1,@_);
538 return $x if $x->modify('bneg');
539 # for +0 dont negate (to have always normalized)
540 return $x if $x->is_zero();
541 $x->{sign} =~ tr/+\-/-+/; # does nothing for NaN
542 # $x->round($a,$p,$r); # changing this makes $x - $y modify $y!!
548 # Compares 2 values. Returns one of undef, <0, =0, >0. (suitable for sort)
549 # (BINT or num_str, BINT or num_str) return cond_code
550 my ($self,$x,$y) = objectify(2,@_);
552 if (($x->{sign} !~ /^[+-]$/) || ($y->{sign} !~ /^[+-]$/))
554 # handle +-inf and NaN
555 return undef if (($x->{sign} eq $nan) || ($y->{sign} eq $nan));
556 return 0 if ($x->{sign} eq $y->{sign}) && ($x->{sign} =~ /^[+-]inf$/);
557 return +1 if $x->{sign} eq '+inf';
558 return -1 if $x->{sign} eq '-inf';
559 return -1 if $y->{sign} eq '+inf';
560 return +1 if $y->{sign} eq '-inf';
563 &cmp($x->{value},$y->{value},$x->{sign},$y->{sign}) <=> 0;
568 # Compares 2 values, ignoring their signs.
569 # Returns one of undef, <0, =0, >0. (suitable for sort)
570 # (BINT, BINT) return cond_code
571 my ($self,$x,$y) = objectify(2,@_);
572 return undef if (($x->{sign} eq $nan) || ($y->{sign} eq $nan));
573 #acmp($x->{value},$y->{value}) <=> 0;
574 $CALC->_acmp($x->{value},$y->{value}) <=> 0;
579 # add second arg (BINT or string) to first (BINT) (modifies first)
580 # return result as BINT
581 my ($self,$x,$y,$a,$p,$r) = objectify(2,@_);
583 return $x if $x->modify('badd');
584 return $x->bnan() if (($x->{sign} !~ /^[+-]$/) || ($y->{sign} !~ /^[+-]$/));
586 my @bn = ($a,$p,$r,$y); # make array for round calls
587 # speed: no add for 0+y or x+0
588 return $x->round(@bn) if $y->is_zero(); # x+0
589 if ($x->is_zero()) # 0+y
591 # make copy, clobbering up x
592 $x->{value} = $CALC->_copy($y->{value});
593 #$x->{value} = [ @{$y->{value}} ];
594 $x->{sign} = $y->{sign} || $nan;
595 return $x->round(@bn);
599 my $xv = $x->{value};
600 my $yv = $y->{value};
601 my ($sx, $sy) = ( $x->{sign}, $y->{sign} ); # get signs
605 $CALC->_add($xv,$yv); # if same sign, absolute add
610 my $a = $CALC->_acmp ($yv,$xv); # absolute compare
613 #print "swapped sub (a=$a)\n";
614 $CALC->_sub($yv,$xv,1); # absolute sub w/ swapped params
619 # speedup, if equal, set result to 0
620 #print "equal sub, result = 0\n";
621 $x->{value} = $CALC->_zero();
626 #print "unswapped sub (a=$a)\n";
627 $CALC->_sub($xv, $yv); # absolute sub
631 return $x->round(@bn);
636 # (BINT or num_str, BINT or num_str) return num_str
637 # subtract second arg from first, modify first
638 my ($self,$x,$y,$a,$p,$r) = objectify(2,@_);
640 return $x if $x->modify('bsub');
641 $x->badd($y->bneg()); # badd does not leave internal zeros
642 $y->bneg(); # refix y, assumes no one reads $y in between
643 return $x->round($a,$p,$r,$y);
648 # increment arg by one
649 my ($self,$x,$a,$p,$r) = objectify(1,@_);
650 # my $x = shift; $x = $class->new($x) unless ref $x; my $self = ref($x);
651 return $x if $x->modify('binc');
652 $x->badd($self->_one())->round($a,$p,$r);
657 # decrement arg by one
658 my ($self,$x,$a,$p,$r) = objectify(1,@_);
659 return $x if $x->modify('bdec');
660 $x->badd($self->_one('-'))->round($a,$p,$r);
665 # (BINT or num_str, BINT or num_str) return BINT
666 # does not modify arguments, but returns new object
667 # Lowest Common Multiplicator
669 my $y = shift; my ($x);
676 $x = $class->new($y);
678 while (@_) { $x = _lcm($x,shift); }
684 # (BINT or num_str, BINT or num_str) return BINT
685 # does not modify arguments, but returns new object
686 # GCD -- Euclids algorithm, variant C (Knuth Vol 3, pg 341 ff)
688 my $y = shift; my ($x);
695 $x = $class->new($y);
698 if ($CALC->can('_gcd'))
702 $y = shift; $y = $class->new($y) if !ref($y);
703 next if $y->is_zero();
704 return $x->bnan() if $y->{sign} !~ /^[+-]$/; # y NaN?
705 $x->{value} = $CALC->_gcd($x->{value},$y->{value}); last if $x->is_one();
712 $x = _gcd($x,shift); last if $x->is_one(); # _gcd handles NaN
721 # (BINT or num_str, BINT or num_str) return BINT
722 my ($self,$x,$y) = objectify(2,@_);
724 return $x if $x->modify('bmod');
725 (&bdiv($self,$x,$y))[1];
730 # (num_str or BINT) return BINT
731 # represent ~x as twos-complement number
732 my ($self,$x) = objectify(1,@_);
733 return $x if $x->modify('bnot');
734 $x->bneg(); $x->bdec(); # was: bsub(-1,$x);, time it someday
740 # return true if arg (BINT or num_str) is zero (array '+', '0')
741 #my ($self,$x) = objectify(1,@_);
742 my $x = shift; $x = $class->new($x) unless ref $x;
744 return 0 if $x->{sign} !~ /^[+-]$/;
745 return $CALC->_is_zero($x->{value});
746 #return (@{$x->{value}} == 1) && ($x->{sign} eq '+')
747 # && ($x->{value}->[0] == 0);
752 # return true if arg (BINT or num_str) is NaN
753 #my ($self,$x) = objectify(1,@_);
754 my $x = shift; $x = $class->new($x) unless ref $x;
755 return ($x->{sign} eq $nan);
760 # return true if arg (BINT or num_str) is +-inf
761 #my ($self,$x) = objectify(1,@_);
762 my $x = shift; $x = $class->new($x) unless ref $x;
763 my $sign = shift || '';
765 return $x->{sign} =~ /^[+-]inf$/ if $sign eq '';
766 return $x->{sign} =~ /^[$sign]inf$/;
771 # return true if arg (BINT or num_str) is +1
772 # or -1 if sign is given
773 #my ($self,$x) = objectify(1,@_);
774 my $x = shift; $x = $class->new($x) unless ref $x;
775 my $sign = shift || '+';
777 # catch also NaN, +inf, -inf
778 return 0 if $x->{sign} ne $sign || $x->{sign} !~ /^[+-]$/;
779 return $CALC->_is_one($x->{value});
780 #return (@{$x->{value}} == 1) && ($x->{sign} eq $sign)
781 # && ($x->{value}->[0] == 1);
786 # return true when arg (BINT or num_str) is odd, false for even
787 my $x = shift; $x = $class->new($x) unless ref $x;
788 #my ($self,$x) = objectify(1,@_);
790 return 0 if $x->{sign} !~ /^[+-]$/; # NaN & +-inf aren't
791 return $CALC->_is_odd($x->{value});
792 #return (($x->{sign} ne $nan) && ($x->{value}->[0] & 1));
797 # return true when arg (BINT or num_str) is even, false for odd
798 my $x = shift; $x = $class->new($x) unless ref $x;
799 #my ($self,$x) = objectify(1,@_);
801 return 0 if $x->{sign} !~ /^[+-]$/; # NaN & +-inf aren't
802 return $CALC->_is_even($x->{value});
803 #return (($x->{sign} ne $nan) && (!($x->{value}->[0] & 1)));
804 #return (($x->{sign} !~ /^[+-]$/) && ($CALC->_is_even($x->{value})));
809 # return true when arg (BINT or num_str) is positive (>= 0)
810 my $x = shift; $x = $class->new($x) unless ref $x;
811 return ($x->{sign} =~ /^\+/);
816 # return true when arg (BINT or num_str) is negative (< 0)
817 my $x = shift; $x = $class->new($x) unless ref $x;
818 return ($x->{sign} =~ /^-/);
821 ###############################################################################
825 # multiply two numbers -- stolen from Knuth Vol 2 pg 233
826 # (BINT or num_str, BINT or num_str) return BINT
827 my ($self,$x,$y,$a,$p,$r) = objectify(2,@_);
829 return $x if $x->modify('bmul');
830 return $x->bnan() if (($x->{sign} !~ /^[+-]$/) || ($y->{sign} !~ /^[+-]$/));
832 return $x->bzero() if $x->is_zero() || $y->is_zero(); # handle result = 0
833 $x->{sign} = $x->{sign} eq $y->{sign} ? '+' : '-'; # +1 * +1 or -1 * -1 => +
834 $CALC->_mul($x->{value},$y->{value}); # do actual math
835 return $x->round($a,$p,$r,$y);
840 # (dividend: BINT or num_str, divisor: BINT or num_str) return
841 # (BINT,BINT) (quo,rem) or BINT (only rem)
842 my ($self,$x,$y,$a,$p,$r) = objectify(2,@_);
844 return $x if $x->modify('bdiv');
846 # 5 / 0 => +inf, -6 / 0 => -inf (0 / 0 => 1 or +inf or NaN?)
848 # ? ($x->binf($x->{sign}),binf($x->{sign})) : $x->binf($x->{sign})
849 # if ($x->{sign} =~ /^[+-]$/ && $y->is_zero());
852 return wantarray ? ($x->bnan(),bnan()) : $x->bnan()
853 if ($x->{sign} !~ /^[+-]$/ || $y->{sign} !~ /^[+-]$/ || $y->is_zero());
856 return wantarray ? ($x,$self->bzero()) : $x if $x->is_zero();
858 # Is $x in the interval [0, $y) ?
859 my $cmp = $CALC->_acmp($x->{value},$y->{value});
860 if (($cmp < 0) and ($x->{sign} eq $y->{sign}))
862 return $x->bzero() unless wantarray;
863 my $t = $x->copy(); # make copy first, because $x->bzero() clobbers $x
864 return ($x->bzero(),$t);
868 # shortcut, both are the same, so set to +/- 1
869 $x->_one( ($x->{sign} ne $y->{sign} ? '-' : '+') );
870 return $x unless wantarray;
871 return ($x,$self->bzero());
874 # calc new sign and in case $y == +/- 1, return $x
875 $x->{sign} = ($x->{sign} ne $y->{sign} ? '-' : '+');
876 # check for / +-1 (cant use $y->is_one due to '-'
877 if (($y == 1) || ($y == -1)) # slow!
878 #if ((@{$y->{value}} == 1) && ($y->{value}->[0] == 1))
880 return wantarray ? ($x,$self->bzero()) : $x;
884 my $rem = $self->bzero();
885 $rem->{sign} = $y->{sign};
886 #($x->{value},$rem->{value}) = div($x->{value},$y->{value});
887 ($x->{value},$rem->{value}) = $CALC->_div($x->{value},$y->{value});
888 # do not leave rest "-0";
889 # $rem->{sign} = '+' if (@{$rem->{value}} == 1) && ($rem->{value}->[0] == 0);
890 $rem->{sign} = '+' if $CALC->_is_zero($rem->{value});
891 if (($x->{sign} eq '-') and (!$rem->is_zero()))
895 $x->round($a,$p,$r,$y);
898 $rem->round($a,$p,$r,$x,$y);
899 return ($x,$y-$rem) if $x->{sign} eq '-'; # was $x,$rem
907 # (BINT or num_str, BINT or num_str) return BINT
908 # compute power of two numbers -- stolen from Knuth Vol 2 pg 233
909 # modifies first argument
910 my ($self,$x,$y,$a,$p,$r) = objectify(2,@_);
912 return $x if $x->modify('bpow');
914 return $x if $x->{sign} =~ /^[+-]inf$/; # -inf/+inf ** x
915 return $x->bnan() if $x->{sign} eq $nan || $y->{sign} eq $nan;
916 return $x->_one() if $y->is_zero();
917 return $x if $x->is_one() || $y->is_one();
918 #if ($x->{sign} eq '-' && @{$x->{value}} == 1 && $x->{value}->[0] == 1)
919 if ($x->{sign} eq '-' && $CALC->_is_one($x->{value}))
921 # if $x == -1 and odd/even y => +1/-1
922 return $y->is_odd() ? $x : $x->babs();
923 # my Casio FX-5500L has a bug here: -1 ** 2 is -1, but -1 * -1 is 1; LOL
925 # 1 ** -y => 1 / (1**y), so do test for negative $y after above's clause
926 return $x->bnan() if $y->{sign} eq '-';
927 return $x if $x->is_zero(); # 0**y => 0 (if not y <= 0)
929 if ($CALC->can('_pow'))
931 $CALC->_pow($x->{value},$y->{value});
932 return $x->round($a,$p,$r);
934 # based on the assumption that shifting in base 10 is fast, and that mul
935 # works faster if numbers are small: we count trailing zeros (this step is
936 # O(1)..O(N), but in case of O(N) we save much more time due to this),
937 # stripping them out of the multiplication, and add $count * $y zeros
938 # afterwards like this:
939 # 300 ** 3 == 300*300*300 == 3*3*3 . '0' x 2 * 3 == 27 . '0' x 6
940 # creates deep recursion?
941 #my $zeros = $x->_trailing_zeros();
944 # $x->brsft($zeros,10); # remove zeros
945 # $x->bpow($y); # recursion (will not branch into here again)
946 # $zeros = $y * $zeros; # real number of zeros to add
947 # $x->blsft($zeros,10);
948 # return $x->round($a,$p,$r);
951 my $pow2 = $self->_one();
952 my $y1 = $class->new($y);
954 while (!$y1->is_one())
956 #print "bpow: p2: $pow2 x: $x y: $y1 r: $res\n";
957 #print "len ",$x->length(),"\n";
958 ($y1,$res)=&bdiv($y1,2);
959 if (!$res->is_zero()) { &bmul($pow2,$x); }
960 if (!$y1->is_zero()) { &bmul($x,$x); }
963 #print "bpow: e p2: $pow2 x: $x y: $y1 r: $res\n";
964 &bmul($x,$pow2) if (!$pow2->is_one());
965 #print "bpow: e p2: $pow2 x: $x y: $y1 r: $res\n";
966 return $x->round($a,$p,$r);
971 # (BINT or num_str, BINT or num_str) return BINT
972 # compute x << y, base n, y >= 0
973 my ($self,$x,$y,$n) = objectify(2,@_);
975 return $x if $x->modify('blsft');
976 return $x->bnan() if ($x->{sign} !~ /^[+-]$/ || $y->{sign} !~ /^[+-]$/);
978 $n = 2 if !defined $n; return $x if $n == 0;
979 return $x->bnan() if $n < 0 || $y->{sign} eq '-';
982 $x->bmul( $self->bpow($n, $y) );
986 # # shortcut (faster) for shifting by 10) since we are in base 10eX
988 # my $src = scalar @{$x->{value}}; # source
989 # my $len = $y->numify(); # shift-len as normal int
990 # my $rem = $len % 5; # reminder to shift
991 # my $dst = $src + int($len/5); # destination
993 # my $v = $x->{value}; # speed-up
994 # my $vd; # further speedup
995 # #print "src $src:",$v->[$src]||0," dst $dst:",$v->[$dst]||0," rem $rem\n";
996 # $v->[$src] = 0; # avoid first ||0 for speed
999 # $vd = $v->[$src]; $vd = '00000'.$vd;
1000 # #print "s $src d $dst '$vd' ";
1001 # $vd = substr($vd,-5+$rem,5-$rem);
1003 # $vd .= $src > 0 ? substr('00000'.$v->[$src-1],-5,$rem) : '0' x $rem;
1005 # $vd = substr($vd,-5,5) if length($vd) > 5;
1007 # $v->[$dst] = int($vd);
1010 # # set lowest parts to 0
1011 # while ($dst >= 0) { $v->[$dst--] = 0; }
1012 # # fix spurios last zero element
1013 # splice @$v,-1 if $v->[-1] == 0;
1014 # #print "elems: "; my $i = 0;
1015 # #foreach (reverse @$v) { print "$i $_ "; $i++; } print "\n";
1016 # # old way: $x->bmul( $self->bpow($n, $y) );
1023 # (BINT or num_str, BINT or num_str) return BINT
1024 # compute x >> y, base n, y >= 0
1025 my ($self,$x,$y,$n) = objectify(2,@_);
1027 return $x if $x->modify('brsft');
1028 return $x->bnan() if ($x->{sign} !~ /^[+-]$/ || $y->{sign} !~ /^[+-]$/);
1030 $n = 2 if !defined $n; return $x->bnan() if $n <= 0 || $y->{sign} eq '-';
1033 scalar bdiv($x, $self->bpow($n, $y));
1037 # # shortcut (faster) for shifting by 10)
1039 # my $dst = 0; # destination
1040 # my $src = $y->numify(); # as normal int
1041 # my $rem = $src % 5; # reminder to shift
1042 # $src = int($src / 5); # source
1043 # my $len = scalar @{$x->{value}} - $src; # elems to go
1044 # my $v = $x->{value}; # speed-up
1047 # splice (@$v,0,$src); # even faster, 38.4 => 39.3
1052 # $v->[scalar @$v] = 0; # avoid || 0 test inside loop
1053 # while ($dst < $len)
1055 # $vd = '00000'.$v->[$src];
1056 # #print "$dst $src '$vd' ";
1057 # $vd = substr($vd,-5,5-$rem);
1060 # $vd = substr('00000'.$v->[$src],-$rem,$rem) . $vd;
1063 # $vd = substr($vd,-5,5) if length($vd) > 5;
1064 # $v->[$dst] = int($vd);
1067 # splice (@$v,$dst) if $dst > 0; # kill left-over array elems
1068 # pop @$v if $v->[-1] == 0; # kill last element
1070 # # old way: scalar bdiv($x, $self->bpow($n, $y));
1077 #(BINT or num_str, BINT or num_str) return BINT
1079 my ($self,$x,$y,$a,$p,$r) = objectify(2,@_);
1081 return $x if $x->modify('band');
1083 return $x->bnan() if ($x->{sign} !~ /^[+-]$/ || $y->{sign} !~ /^[+-]$/);
1084 return $x->bzero() if $y->is_zero();
1086 if ($CALC->can('_and'))
1088 $CALC->_and($x->{value},$y->{value});
1089 return $x->round($a,$p,$r);
1092 my $m = new Math::BigInt 1; my ($xr,$yr);
1093 my $x10000 = new Math::BigInt (0x10000);
1094 my $y1 = copy(ref($x),$y); # make copy
1095 my $x1 = $x->copy(); $x->bzero(); # modify x in place!
1096 while (!$x1->is_zero() && !$y1->is_zero())
1098 ($x1, $xr) = bdiv($x1, $x10000);
1099 ($y1, $yr) = bdiv($y1, $x10000);
1100 #print ref($xr), " $xr ", $xr->numify(),"\n";
1101 #print ref($yr), " $yr ", $yr->numify(),"\n";
1102 #print "res: ",$yr->numify() & $xr->numify(),"\n";
1103 my $u = bmul( $class->new( $xr->numify() & $yr->numify() ), $m);
1105 $x->badd( bmul( $class->new( $xr->numify() & $yr->numify() ), $m));
1108 return $x->round($a,$p,$r);
1113 #(BINT or num_str, BINT or num_str) return BINT
1115 my ($self,$x,$y,$a,$p,$r) = objectify(2,@_);
1117 return $x if $x->modify('bior');
1119 return $x->bnan() if ($x->{sign} !~ /^[+-]$/ || $y->{sign} !~ /^[+-]$/);
1120 return $x if $y->is_zero();
1121 if ($CALC->can('_or'))
1123 $CALC->_or($x->{value},$y->{value});
1124 return $x->round($a,$p,$r);
1127 my $m = new Math::BigInt 1; my ($xr,$yr);
1128 my $x10000 = new Math::BigInt (0x10000);
1129 my $y1 = copy(ref($x),$y); # make copy
1130 my $x1 = $x->copy(); $x->bzero(); # modify x in place!
1131 while (!$x1->is_zero() || !$y1->is_zero())
1133 ($x1, $xr) = bdiv($x1,$x10000);
1134 ($y1, $yr) = bdiv($y1,$x10000);
1135 $x->badd( bmul( $class->new( $xr->numify() | $yr->numify() ), $m));
1138 return $x->round($a,$p,$r);
1143 #(BINT or num_str, BINT or num_str) return BINT
1145 my ($self,$x,$y,$a,$p,$r) = objectify(2,@_);
1147 return $x if $x->modify('bxor');
1149 return $x->bnan() if ($x->{sign} !~ /^[+-]$/ || $y->{sign} !~ /^[+-]$/);
1150 return $x if $y->is_zero();
1151 return $x->bzero() if $x == $y; # shortcut
1153 if ($CALC->can('_xor'))
1155 $CALC->_xor($x->{value},$y->{value});
1156 return $x->round($a,$p,$r);
1159 my $m = new Math::BigInt 1; my ($xr,$yr);
1160 my $x10000 = new Math::BigInt (0x10000);
1161 my $y1 = copy(ref($x),$y); # make copy
1162 my $x1 = $x->copy(); $x->bzero(); # modify x in place!
1163 while (!$x1->is_zero() || !$y1->is_zero())
1165 ($x1, $xr) = bdiv($x1, $x10000);
1166 ($y1, $yr) = bdiv($y1, $x10000);
1167 $x->badd( bmul( $class->new( $xr->numify() ^ $yr->numify() ), $m));
1170 return $x->round($a,$p,$r);
1175 my ($self,$x) = objectify(1,@_);
1177 my $e = $CALC->_len($x->{value});
1178 # # fallback, since we do not know the underlying representation
1179 #my $es = "$x"; my $c = 0; $c = 1 if $es =~ /^[+-]/; # if lib returns '+123'
1180 #my $e = CORE::length($es)-$c;
1181 return wantarray ? ($e,0) : $e;
1186 # return the nth decimal digit, negative values count backward, 0 is right
1190 return $CALC->_digit($x->{value},$n);
1195 # return the amount of trailing zeros in $x
1197 $x = $class->new($x) unless ref $x;
1199 return 0 if $x->is_zero() || $x->is_nan() || $x->is_inf();
1201 return $CALC->_zeros($x->{value}) if $CALC->can('_zeros');
1203 # if not: since we do not know underlying internal representation:
1204 my $es = "$x"; $es =~ /([0]*)$/;
1206 return 0 if !defined $1; # no zeros
1207 return CORE::length("$1"); # as string, not as +0!
1212 my ($self,$x) = objectify(1,@_);
1214 return $x->bnan() if $x->{sign} =~ /\-|$nan/; # -x or NaN => NaN
1215 return $x->bzero() if $x->is_zero(); # 0 => 0
1216 return $x if $x == 1; # 1 => 1
1218 my $y = $x->copy(); # give us one more digit accur.
1219 my $l = int($x->length()/2);
1222 $x->binc(); # keep ref($x), but modify it
1225 # print "x: $y guess $x\n";
1227 my $last = $self->bzero();
1239 # return a copy of the exponent (here always 0, NaN or 1 for $m == 0)
1240 my ($self,$x) = objectify(1,@_);
1242 return bnan() if $x->is_nan();
1243 my $e = $class->bzero();
1244 return $e->binc() if $x->is_zero();
1245 $e += $x->_trailing_zeros();
1251 # return a copy of the mantissa (here always $self)
1252 my ($self,$x) = objectify(1,@_);
1254 return bnan() if $x->is_nan();
1256 # that's inefficient
1257 my $zeros = $m->_trailing_zeros();
1258 $m /= 10 ** $zeros if $zeros != 0;
1264 # return a copy of both the exponent and the mantissa (here 0 and self)
1266 $self = $class->new($self) unless ref $self;
1268 return ($self->mantissa(),$self->exponent());
1271 ##############################################################################
1272 # rounding functions
1276 # precision: round to the $Nth digit left (+$n) or right (-$n) from the '.'
1277 # $n == 0 => round to integer
1278 my $x = shift; $x = $class->new($x) unless ref $x;
1279 my ($scale,$mode) = $x->_scale_p($precision,$rnd_mode,@_);
1280 return $x if !defined $scale; # no-op
1282 # no-op for BigInts if $n <= 0
1283 return $x if $scale <= 0;
1285 $x->bround( $x->length()-$scale, $mode);
1288 sub _scan_for_nonzero
1294 my $len = $x->length();
1295 return 0 if $len == 1; # '5' is trailed by invisible zeros
1296 my $follow = $pad - 1;
1297 return 0 if $follow > $len || $follow < 1;
1298 #print "checking $x $r\n";
1300 # since we do not know underlying represention of $x, use decimal string
1301 #my $r = substr ($$xs,-$follow);
1302 my $r = substr ("$x",-$follow);
1303 return 1 if $r =~ /[^0]/; return 0;
1308 # to make life easier for switch between MBF and MBI (autoload fxxx()
1309 # like MBF does for bxxx()?)
1311 return $x->bround(@_);
1316 # accuracy: +$n preserve $n digits from left,
1317 # -$n preserve $n digits from right (f.i. for 0.1234 style in MBF)
1319 # and overwrite the rest with 0's, return normalized number
1320 # do not return $x->bnorm(), but $x
1321 my $x = shift; $x = $class->new($x) unless ref $x;
1322 my ($scale,$mode) = $x->_scale_a($accuracy,$rnd_mode,@_);
1323 return $x if !defined $scale; # no-op
1325 # print "MBI round: $x to $scale $mode\n";
1326 # -scale means what? tom? hullo? -$scale needed by MBF round, but what for?
1327 return $x if $x->is_nan() || $x->is_zero() || $scale == 0;
1329 # we have fewer digits than we want to scale to
1330 my $len = $x->length();
1331 # print "$len $scale\n";
1332 return $x if $len < abs($scale);
1334 # count of 0's to pad, from left (+) or right (-): 9 - +6 => 3, or |-6| => 6
1335 my ($pad,$digit_round,$digit_after);
1336 $pad = $len - $scale;
1337 $pad = abs($scale)+1 if $scale < 0;
1338 # do not use digit(), it is costly for binary => decimal
1339 #$digit_round = '0'; $digit_round = $x->digit($pad) if $pad < $len;
1340 #$digit_after = '0'; $digit_after = $x->digit($pad-1) if $pad > 0;
1341 my $xs = $CALC->_str($x->{value});
1343 # pad: 123: 0 => -1, at 1 => -2, at 2 => -3, at 3 => -4
1344 # pad+1: 123: 0 => 0, at 1 => -1, at 2 => -2, at 3 => -3
1345 $digit_round = '0'; $digit_round = substr($$xs,$pl,1) if $pad <= $len;
1346 $pl++; $pl ++ if $pad >= $len;
1347 $digit_after = '0'; $digit_after = substr($$xs,$pl,1)
1350 #my $d_round = '0'; $d_round = $x->digit($pad) if $pad < $len;
1351 #my $d_after = '0'; $d_after = $x->digit($pad-1) if $pad > 0;
1352 # print "$pad $pl $$xs $digit_round:$d_round $digit_after:$d_after\n";
1354 # in case of 01234 we round down, for 6789 up, and only in case 5 we look
1355 # closer at the remaining digits of the original $x, remember decision
1356 my $round_up = 1; # default round up
1358 ($mode eq 'trunc') || # trunc by round down
1359 ($digit_after =~ /[01234]/) || # round down anyway,
1361 ($digit_after eq '5') && # not 5000...0000
1362 ($x->_scan_for_nonzero($pad,$xs) == 0) &&
1364 ($mode eq 'even') && ($digit_round =~ /[24680]/) ||
1365 ($mode eq 'odd') && ($digit_round =~ /[13579]/) ||
1366 ($mode eq '+inf') && ($x->{sign} eq '-') ||
1367 ($mode eq '-inf') && ($x->{sign} eq '+') ||
1368 ($mode eq 'zero') # round down if zero, sign adjusted below
1370 # allow rounding one place left of mantissa
1371 #print "$pad $len $scale\n";
1372 # this is triggering warnings, and buggy for $scale < 0
1373 #if (-$scale != $len)
1375 # old code, depend on internal representation
1376 # split mantissa at $pad and then pad with zeros
1377 #my $s5 = int($pad / 5);
1381 # $x->{value}->[$i++] = 0; # replace with 5 x 0
1383 #$x->{value}->[$s5] = '00000'.$x->{value}->[$s5]; # pad with 0
1384 #my $rem = $pad % 5; # so much left over
1387 # #print "remainder $rem\n";
1388 ## #print "elem $x->{value}->[$s5]\n";
1389 # substr($x->{value}->[$s5],-$rem,$rem) = '0' x $rem; # stamp w/ '0'
1391 #$x->{value}->[$s5] = int ($x->{value}->[$s5]); # str '05' => int '5'
1392 #print ${$CALC->_str($pad->{value})}," $len\n";
1393 if (($pad > 0) && ($pad <= $len))
1395 substr($$xs,-$pad,$pad) = '0' x $pad;
1396 $x->{value} = $CALC->_new($xs); # put back in
1400 $x->{value} = $CALC->_zero(); # round to '0'
1402 #print "res $$xs\n";
1404 # move this later on after the inc of the string
1405 #$x->{value} = $CALC->_new($xs); # put back in
1406 if ($round_up) # what gave test above?
1408 $pad = $len if $scale < 0; # tlr: whack 0.51=>1.0
1409 # modify $x in place, undef, undef to avoid rounding
1410 # str creation much faster than 10 ** something
1411 $x->badd( Math::BigInt->new($x->{sign}.'1'.'0'x$pad) );
1412 # increment string in place, to avoid dec=>hex for the '1000...000'
1416 #$x->{value} = $CALC->_new($xs); # put back in
1422 # return integer less or equal then number, since it is already integer,
1423 # always returns $self
1424 my ($self,$x,$a,$p,$r) = objectify(1,@_);
1426 # not needed: return $x if $x->modify('bfloor');
1428 return $x->round($a,$p,$r);
1433 # return integer greater or equal then number, since it is already integer,
1434 # always returns $self
1435 my ($self,$x,$a,$p,$r) = objectify(1,@_);
1437 # not needed: return $x if $x->modify('bceil');
1439 return $x->round($a,$p,$r);
1442 ##############################################################################
1443 # private stuff (internal use only)
1447 # internal speedup, set argument to 1, or create a +/- 1
1449 #my $x = $self->bzero(); $x->{value} = [ 1 ]; $x->{sign} = shift || '+'; $x;
1450 my $x = $self->bzero(); $x->{value} = $CALC->_one();
1451 $x->{sign} = shift || '+';
1457 # Overload will swap params if first one is no object ref so that the first
1458 # one is always an object ref. In this case, third param is true.
1459 # This routine is to overcome the effect of scalar,$object creating an object
1460 # of the class of this package, instead of the second param $object. This
1461 # happens inside overload, when the overload section of this package is
1462 # inherited by sub classes.
1463 # For overload cases (and this is used only there), we need to preserve the
1464 # args, hence the copy().
1465 # You can override this method in a subclass, the overload section will call
1466 # $object->_swap() to make sure it arrives at the proper subclass, with some
1467 # exceptions like '+' and '-'.
1469 # object, (object|scalar) => preserve first and make copy
1470 # scalar, object => swapped, re-swap and create new from first
1471 # (using class of second object, not $class!!)
1472 my $self = shift; # for override in subclass
1473 #print "swap $self 0:$_[0] 1:$_[1] 2:$_[2]\n";
1476 my $c = ref ($_[0]) || $class; # fallback $class should not happen
1477 return ( $c->new($_[1]), $_[0] );
1481 return ( $_[0]->copy(), $_[1] );
1487 # check for strings, if yes, return objects instead
1489 # the first argument is number of args objectify() should look at it will
1490 # return $count+1 elements, the first will be a classname. This is because
1491 # overloaded '""' calls bstr($object,undef,undef) and this would result in
1492 # useless objects beeing created and thrown away. So we cannot simple loop
1493 # over @_. If the given count is 0, all arguments will be used.
1495 # If the second arg is a ref, use it as class.
1496 # If not, try to use it as classname, unless undef, then use $class
1497 # (aka Math::BigInt). The latter shouldn't happen,though.
1500 # $x->badd(1); => ref x, scalar y
1501 # Class->badd(1,2); => classname x (scalar), scalar x, scalar y
1502 # Class->badd( Class->(1),2); => classname x (scalar), ref x, scalar y
1503 # Math::BigInt::badd(1,2); => scalar x, scalar y
1504 # In the last case we check number of arguments to turn it silently into
1505 # $class,1,2. (We cannot take '1' as class ;o)
1506 # badd($class,1) is not supported (it should, eventually, try to add undef)
1507 # currently it tries 'Math::BigInt' + 1, which will not work.
1509 my $count = abs(shift || 0);
1511 #print caller(),"\n";
1513 my @a; # resulting array
1516 # okay, got object as first
1521 # nope, got 1,2 (Class->xxx(1) => Class,1 and not supported)
1523 #print "@_\n"; sleep(1);
1524 $a[0] = shift if $_[0] =~ /^[A-Z].*::/; # classname as first?
1526 #print caller(),"\n";
1527 # print "Now in objectify, my class is today $a[0]\n";
1536 $k = $a[0]->new($k);
1538 elsif (ref($k) ne $a[0])
1540 # foreign object, try to convert to integer
1541 $k->can('as_number') ? $k = $k->as_number() : $k = $a[0]->new($k);
1555 $k = $a[0]->new($k);
1557 elsif (ref($k) ne $a[0])
1559 # foreign object, try to convert to integer
1560 $k->can('as_number') ? $k = $k->as_number() : $k = $a[0]->new($k);
1564 push @a,@_; # return other params, too
1569 # print "o $i $a[0]\n" if $i == 0;
1570 # print "o $i ",ref($_),"\n" if $i != 0; $i++;
1572 #print "objectify done: would return ",scalar @a," values\n";
1573 #print caller(1),"\n" unless wantarray;
1574 die "$class objectify needs list context" unless wantarray;
1581 #print "import $self @_\n";
1582 my @a = @_; my $l = scalar @_; my $j = 0;
1583 for ( my $i = 0; $i < $l ; $i++,$j++ )
1585 if ($_[$i] eq ':constant')
1587 # this causes overlord er load to step in
1588 overload::constant integer => sub { $self->new(shift) };
1589 splice @a, $j, 1; $j --;
1591 elsif ($_[$i] =~ /^lib$/i)
1593 # this causes a different low lib to take care...
1594 $CALC = $_[$i+1] || $CALC;
1595 my $s = 2; $s = 1 if @a-$j < 2; # avoid "cannot modify non-existant..."
1596 splice @a, $j, $s; $j -= $s;
1599 # any non :constant stuff is handled by our parent, Exporter
1600 # even if @_ is empty, to give it a chance
1601 #$self->SUPER::import(@a); # does not work
1602 $self->export_to_level(1,$self,@a); # need this instead
1604 # load core math lib
1605 $CALC = 'Math::BigInt::'.$CALC if $CALC !~ /^Math::BigInt/i;
1607 $c =~ s!::!/!g; # XXX portability, e.g. MacOS?
1608 $c .= '.pm' if $c !~ /\.pm$/;
1614 # internal normalization function that strips leading zeros from the array
1615 # args: ref to array
1618 my $cnt = scalar @$s; # get count of parts
1620 #print "strip: cnt $cnt i $i\n";
1621 # '0', '3', '4', '0', '0',
1626 # => fcnt = cnt - i (5-2 => 3, cnt => 5-1 = 4, throw away from 4th pos)
1627 # >= 1: skip first part (this can be zero)
1628 while ($i > 0) { last if $s->[$i] != 0; $i--; }
1629 $i++; splice @$s,$i if ($i < $cnt); # $i cant be 0
1635 # convert a (ref to) big hex string to BigInt, return undef for error
1638 my $x = Math::BigInt->bzero();
1639 return $x->bnan() if $$hs !~ /^[\-\+]?0x[0-9A-Fa-f]+$/;
1641 my $sign = '+'; $sign = '-' if ($$hs =~ /^-/);
1643 $$hs =~ s/^[+-]//; # strip sign
1644 if ($CALC->can('_from_hex'))
1646 $x->{value} = $CALC->_from_hex($hs);
1650 # fallback to pure perl
1651 my $mul = Math::BigInt->bzero(); $mul++;
1652 my $x65536 = Math::BigInt->new(65536);
1653 my $len = CORE::length($$hs)-2;
1654 $len = int($len/4); # 4-digit parts, w/o '0x'
1655 my $val; my $i = -4;
1658 $val = substr($$hs,$i,4);
1659 $val =~ s/^[+-]?0x// if $len == 0; # for last part only because
1660 $val = hex($val); # hex does not like wrong chars
1661 # print "$val ",substr($$hs,$i,4),"\n";
1663 $x += $mul * $val if $val != 0;
1664 $mul *= $x65536 if $len >= 0; # skip last mul
1667 $x->{sign} = $sign if !$x->is_zero(); # no '-0'
1673 # convert a (ref to) big binary string to BigInt, return undef for error
1676 my $x = Math::BigInt->bzero();
1677 return $x->bnan() if $$bs !~ /^[+-]?0b[01]+$/;
1679 my $mul = Math::BigInt->bzero(); $mul++;
1680 my $x256 = Math::BigInt->new(256);
1682 my $sign = '+'; $sign = '-' if ($$bs =~ /^\-/);
1683 $$bs =~ s/^[+-]//; # strip sign
1684 if ($CALC->can('_from_bin'))
1686 $x->{value} = $CALC->_from_bin($bs);
1690 my $len = CORE::length($$bs)-2;
1691 $len = int($len/8); # 8-digit parts, w/o '0b'
1692 my $val; my $i = -8;
1695 $val = substr($$bs,$i,8);
1696 $val =~ s/^[+-]?0b// if $len == 0; # for last part only
1697 #$val = oct('0b'.$val); # does not work on Perl prior to 5.6.0
1698 $val = ('0' x (8-CORE::length($val))).$val if CORE::length($val) < 8;
1699 $val = ord(pack('B8',$val));
1700 # print "$val ",substr($$bs,$i,16),"\n";
1702 $x += $mul * $val if $val != 0;
1703 $mul *= $x256 if $len >= 0; # skip last mul
1706 $x->{sign} = $sign if !$x->is_zero();
1712 # (ref to num_str) return num_str
1713 # internal, take apart a string and return the pieces
1717 $$x =~ s/^\s+//g; # strip white space at front
1718 $$x =~ s/\s+$//g; # strip white space at end
1719 #$$x =~ s/\s+//g; # strip white space (no longer)
1720 return if $$x eq "";
1722 return _from_hex($x) if $$x =~ /^[\-\+]?0x/; # hex string
1723 return _from_bin($x) if $$x =~ /^[\-\+]?0b/; # binary string
1725 return if $$x !~ /^[\-\+]?\.?[0-9]/;
1727 $$x =~ s/(\d)_(\d)/$1$2/g; # strip underscores between digits
1728 $$x =~ s/(\d)_(\d)/$1$2/g; # do twice for 1_2_3
1730 # some possible inputs:
1731 # 2.1234 # 0.12 # 1 # 1E1 # 2.134E1 # 434E-10 # 1.02009E-2
1732 # .2 # 1_2_3.4_5_6 # 1.4E1_2_3 # 1e3 # +.2
1734 #print "input: '$$x' ";
1735 my ($m,$e) = split /[Ee]/,$$x;
1736 $e = '0' if !defined $e || $e eq "";
1737 # print "m '$m' e '$e'\n";
1738 # sign,value for exponent,mantint,mantfrac
1739 my ($es,$ev,$mis,$miv,$mfv);
1741 if ($e =~ /^([+-]?)0*(\d+)$/) # strip leading zeros
1744 #print "'$m' '$e' e: $es $ev ";
1746 return if $m eq '.' || $m eq '';
1747 my ($mi,$mf) = split /\./,$m;
1748 $mi = '0' if !defined $mi;
1749 $mi .= '0' if $mi =~ /^[\-\+]?$/;
1750 $mf = '0' if !defined $mf || $mf eq '';
1751 if ($mi =~ /^([+-]?)0*(\d+)$/) # strip leading zeros
1753 $mis = $1||'+'; $miv = $2;
1754 # print "$mis $miv";
1755 # valid, existing fraction part of mantissa?
1756 return unless ($mf =~ /^(\d*?)0*$/); # strip trailing zeros
1758 #print " split: $mis $miv . $mfv E $es $ev\n";
1759 return (\$mis,\$miv,\$mfv,\$es,\$ev);
1762 return; # NaN, not a number
1767 # an object might be asked to return itself as bigint on certain overloaded
1768 # operations, this does exactly this, so that sub classes can simple inherit
1769 # it or override with their own integer conversion routine
1772 return $self->copy();
1775 ##############################################################################
1776 # internal calculation routines (others are in Math::BigInt::Calc etc)
1780 # post-normalized compare for internal use (honors signs)
1781 # input: ref to value, ref to value, sign, sign
1783 my ($cx,$cy,$sx,$sy) = @_;
1787 return 1 if $sy eq '-'; # 0 check handled above
1788 #return acmp($cx,$cy);
1789 return $CALC->_acmp($cx,$cy);
1794 return -1 if $sy eq '+';
1795 #return acmp($cy,$cx);
1796 return $CALC->_acmp($cy,$cx);
1803 # (BINT or num_str, BINT or num_str) return BINT
1804 # does modify first argument
1807 my $x = shift; my $ty = shift;
1808 return $x->bnan() if ($x->{sign} eq $nan) || ($ty->{sign} eq $nan);
1809 return $x * $ty / bgcd($x,$ty);
1814 # (BINT or num_str, BINT or num_str) return BINT
1815 # does modify first arg
1816 # GCD -- Euclids algorithm E, Knuth Vol 2 pg 296
1818 my $x = shift; my $ty = $class->new(shift); # preserve y, but make class
1819 return $x->bnan() if $x->{sign} !~ /^[+-]$/ || $ty->{sign} !~ /^[+-]$/;
1821 while (!$ty->is_zero())
1823 ($x, $ty) = ($ty,bmod($x,$ty));
1828 ###############################################################################
1829 # this method return 0 if the object can be modified, or 1 for not
1830 # We use a fast use constant statement here, to avoid costly calls. Subclasses
1831 # may override it with special code (f.i. Math::BigInt::Constant does so)
1833 sub modify () { 0; }
1840 Math::BigInt - Arbitrary size integer math package
1847 $x = Math::BigInt->new($str); # defaults to 0
1848 $nan = Math::BigInt->bnan(); # create a NotANumber
1849 $zero = Math::BigInt->bzero();# create a "+0"
1852 $x->is_zero(); # return whether arg is zero or not
1853 $x->is_nan(); # return whether arg is NaN or not
1854 $x->is_one(); # true if arg is +1
1855 $x->is_one('-'); # true if arg is -1
1856 $x->is_odd(); # true if odd, false for even
1857 $x->is_even(); # true if even, false for odd
1858 $x->is_positive(); # true if >= 0
1859 $x->is_negative(); # true if < 0
1860 $x->is_inf(sign); # true if +inf, or -inf (sign is default '+')
1862 $x->bcmp($y); # compare numbers (undef,<0,=0,>0)
1863 $x->bacmp($y); # compare absolutely (undef,<0,=0,>0)
1864 $x->sign(); # return the sign, either +,- or NaN
1865 $x->digit($n); # return the nth digit, counting from right
1866 $x->digit(-$n); # return the nth digit, counting from left
1868 # The following all modify their first argument:
1871 $x->bzero(); # set $x to 0
1872 $x->bnan(); # set $x to NaN
1874 $x->bneg(); # negation
1875 $x->babs(); # absolute value
1876 $x->bnorm(); # normalize (no-op)
1877 $x->bnot(); # two's complement (bit wise not)
1878 $x->binc(); # increment x by 1
1879 $x->bdec(); # decrement x by 1
1881 $x->badd($y); # addition (add $y to $x)
1882 $x->bsub($y); # subtraction (subtract $y from $x)
1883 $x->bmul($y); # multiplication (multiply $x by $y)
1884 $x->bdiv($y); # divide, set $x to quotient
1885 # return (quo,rem) or quo if scalar
1887 $x->bmod($y); # modulus (x % y)
1888 $x->bpow($y); # power of arguments (x ** y)
1889 $x->blsft($y); # left shift
1890 $x->brsft($y); # right shift
1891 $x->blsft($y,$n); # left shift, by base $n (like 10)
1892 $x->brsft($y,$n); # right shift, by base $n (like 10)
1894 $x->band($y); # bitwise and
1895 $x->bior($y); # bitwise inclusive or
1896 $x->bxor($y); # bitwise exclusive or
1897 $x->bnot(); # bitwise not (two's complement)
1899 $x->bsqrt(); # calculate square-root
1901 $x->round($A,$P,$round_mode); # round to accuracy or precision using mode $r
1902 $x->bround($N); # accuracy: preserve $N digits
1903 $x->bfround($N); # round to $Nth digit, no-op for BigInts
1905 # The following do not modify their arguments in BigInt, but do in BigFloat:
1906 $x->bfloor(); # return integer less or equal than $x
1907 $x->bceil(); # return integer greater or equal than $x
1909 # The following do not modify their arguments:
1911 bgcd(@values); # greatest common divisor
1912 blcm(@values); # lowest common multiplicator
1914 $x->bstr(); # normalized string
1915 $x->bsstr(); # normalized string in scientific notation
1916 $x->length(); # return number of digits in number
1917 ($x,$f) = $x->length(); # length of number and length of fraction part
1919 $x->exponent(); # return exponent as BigInt
1920 $x->mantissa(); # return mantissa as BigInt
1921 $x->parts(); # return (mantissa,exponent) as BigInt
1922 $x->copy(); # make a true copy of $x (unlike $y = $x;)
1923 $x->as_number(); # return as BigInt (in BigInt: same as copy())
1927 All operators (inlcuding basic math operations) are overloaded if you
1928 declare your big integers as
1930 $i = new Math::BigInt '123_456_789_123_456_789';
1932 Operations with overloaded operators preserve the arguments which is
1933 exactly what you expect.
1937 =item Canonical notation
1939 Big integer values are strings of the form C</^[+-]\d+$/> with leading
1942 '-0' canonical value '-0', normalized '0'
1943 ' -123_123_123' canonical value '-123123123'
1944 '1_23_456_7890' canonical value '1234567890'
1948 Input values to these routines may be either Math::BigInt objects or
1949 strings of the form C</^\s*[+-]?[\d]+\.?[\d]*E?[+-]?[\d]*$/>.
1951 You can include one underscore between any two digits.
1953 This means integer values like 1.01E2 or even 1000E-2 are also accepted.
1954 Non integer values result in NaN.
1956 Math::BigInt::new() defaults to 0, while Math::BigInt::new('') results
1959 bnorm() on a BigInt object is now effectively a no-op, since the numbers
1960 are always stored in normalized form. On a string, it creates a BigInt
1965 Output values are BigInt objects (normalized), except for bstr(), which
1966 returns a string in normalized form.
1967 Some routines (C<is_odd()>, C<is_even()>, C<is_zero()>, C<is_one()>,
1968 C<is_nan()>) return true or false, while others (C<bcmp()>, C<bacmp()>)
1969 return either undef, <0, 0 or >0 and are suited for sort.
1973 =head1 ACCURACY and PRECISION
1975 Since version v1.33, Math::BigInt and Math::BigFloat have full support for
1976 accuracy and precision based rounding, both automatically after every
1977 operation as well as manually.
1979 This section describes the accuracy/precision handling in Math::Big* as it
1980 used to be and as it is now, complete with an explanation of all terms and
1983 Not yet implemented things (but with correct description) are marked with '!',
1984 things that need to be answered are marked with '?'.
1986 In the next paragraph follows a short description of terms used here (because
1987 these may differ from terms used by other people or documentation).
1989 During the rest of this document, the shortcuts A (for accuracy), P (for
1990 precision), F (fallback) and R (rounding mode) will be used.
1994 A fixed number of digits before (positive) or after (negative)
1995 the decimal point. For example, 123.45 has a precision of -2. 0 means an
1996 integer like 123 (or 120). A precision of 2 means two digits to the left
1997 of the decimal point are zero, so 123 with P = 1 becomes 120. Note that
1998 numbers with zeros before the decimal point may have different precisions,
1999 because 1200 can have p = 0, 1 or 2 (depending on what the inital value
2000 was). It could also have p < 0, when the digits after the decimal point
2003 !The string output of such a number should be padded with zeros:
2005 ! Initial value P Result String
2006 ! 1234.01 -3 1000 1000
2008 ! 1234.5 -1 1230 1230
2009 ! 1234.001 1 1234 1234.0
2010 ! 1234.01 0 1234 1234
2011 ! 1234.01 2 1234.01 1234.01
2012 ! 1234.01 5 1234.01 1234.01000
2016 Number of significant digits. Leading zeros are not counted. A
2017 number may have an accuracy greater than the non-zero digits
2018 when there are zeros in it or trailing zeros. For example, 123.456 has
2019 A of 6, 10203 has 5, 123.0506 has 7, 123.450000 has 8 and 0.000123 has 3.
2023 When both A and P are undefined, this is used as a fallback accuracy.
2025 =head2 Rounding mode R
2027 When rounding a number, different 'styles' or 'kinds'
2028 of rounding are possible. (Note that random rounding, as in
2029 Math::Round, is not implemented.)
2035 truncation invariably removes all digits following the
2036 rounding place, replacing them with zeros. Thus, 987.65 rounded
2037 to tens (P=1) becomes 980, and rounded to the fourth sigdig
2038 becomes 987.6 (A=4). 123.456 rounded to the second place after the
2039 decimal point (P=-2) becomes 123.46.
2041 All other implemented styles of rounding attempt to round to the
2042 "nearest digit." If the digit D immediately to the right of the
2043 rounding place (skipping the decimal point) is greater than 5, the
2044 number is incremented at the rounding place (possibly causing a
2045 cascade of incrementation): e.g. when rounding to units, 0.9 rounds
2046 to 1, and -19.9 rounds to -20. If D < 5, the number is similarly
2047 truncated at the rounding place: e.g. when rounding to units, 0.4
2048 rounds to 0, and -19.4 rounds to -19.
2050 However the results of other styles of rounding differ if the
2051 digit immediately to the right of the rounding place (skipping the
2052 decimal point) is 5 and if there are no digits, or no digits other
2053 than 0, after that 5. In such cases:
2057 rounds the digit at the rounding place to 0, 2, 4, 6, or 8
2058 if it is not already. E.g., when rounding to the first sigdig, 0.45
2059 becomes 0.4, -0.55 becomes -0.6, but 0.4501 becomes 0.5.
2063 rounds the digit at the rounding place to 1, 3, 5, 7, or 9 if
2064 it is not already. E.g., when rounding to the first sigdig, 0.45
2065 becomes 0.5, -0.55 becomes -0.5, but 0.5501 becomes 0.6.
2069 round to plus infinity, i.e. always round up. E.g., when
2070 rounding to the first sigdig, 0.45 becomes 0.5, -0.55 becomes -0.5,
2071 and 0.4501 also becomes 0.5.
2075 round to minus infinity, i.e. always round down. E.g., when
2076 rounding to the first sigdig, 0.45 becomes 0.4, -0.55 becomes -0.6,
2077 but 0.4501 becomes 0.5.
2081 round to zero, i.e. positive numbers down, negative ones up.
2082 E.g., when rounding to the first sigdig, 0.45 becomes 0.4, -0.55
2083 becomes -0.5, but 0.4501 becomes 0.5.
2087 The handling of A & P in MBI/MBF (the old core code shipped with Perl
2088 versions <= 5.7.2) is like this:
2094 * ffround($p) is able to round to $p number of digits after the decimal
2096 * otherwise P is unused
2098 =item Accuracy (significant digits)
2100 * fround($a) rounds to $a significant digits
2101 * only fdiv() and fsqrt() take A as (optional) paramater
2102 + other operations simply create the same number (fneg etc), or more (fmul)
2104 + rounding/truncating is only done when explicitly calling one of fround
2105 or ffround, and never for BigInt (not implemented)
2106 * fsqrt() simply hands its accuracy argument over to fdiv.
2107 * the documentation and the comment in the code indicate two different ways
2108 on how fdiv() determines the maximum number of digits it should calculate,
2109 and the actual code does yet another thing
2111 max($Math::BigFloat::div_scale,length(dividend)+length(divisor))
2113 result has at most max(scale, length(dividend), length(divisor)) digits
2115 scale = max(scale, length(dividend)-1,length(divisor)-1);
2116 scale += length(divisior) - length(dividend);
2117 So for lx = 3, ly = 9, scale = 10, scale will actually be 16 (10+9-3).
2118 Actually, the 'difference' added to the scale is calculated from the
2119 number of "significant digits" in dividend and divisor, which is derived
2120 by looking at the length of the mantissa. Which is wrong, since it includes
2121 the + sign (oups) and actually gets 2 for '+100' and 4 for '+101'. Oups
2122 again. Thus 124/3 with div_scale=1 will get you '41.3' based on the strange
2123 assumption that 124 has 3 significant digits, while 120/7 will get you
2124 '17', not '17.1' since 120 is thought to have 2 significant digits.
2125 The rounding after the division then uses the reminder and $y to determine
2126 wether it must round up or down.
2127 ? I have no idea which is the right way. That's why I used a slightly more
2128 ? simple scheme and tweaked the few failing testcases to match it.
2132 This is how it works now:
2136 =item Setting/Accessing
2138 * You can set the A global via $Math::BigInt::accuracy or
2139 $Math::BigFloat::accuracy or whatever class you are using.
2140 * You can also set P globally by using $Math::SomeClass::precision likewise.
2141 * Globals are classwide, and not inherited by subclasses.
2142 * to undefine A, use $Math::SomeCLass::accuracy = undef
2143 * to undefine P, use $Math::SomeClass::precision = undef
2144 * To be valid, A must be > 0, P can have any value.
2145 * If P is negative, this means round to the P'th place to the right of the
2146 decimal point; positive values mean to the left of the decimal point.
2147 P of 0 means round to integer.
2148 * to find out the current global A, take $Math::SomeClass::accuracy
2149 * use $x->accuracy() for the local setting of $x.
2150 * to find out the current global P, take $Math::SomeClass::precision
2151 * use $x->precision() for the local setting
2153 =item Creating numbers
2155 !* When you create a number, there should be a way to define its A & P
2156 * When a number without specific A or P is created, but the globals are
2157 defined, these should be used to round the number immediately and also
2158 stored locally with the number. Thus changing the global defaults later on
2159 will not change the A or P of previously created numbers (i.e., A and P of
2160 $x will be what was in effect when $x was created)
2164 * If A or P are enabled/defined, they are used to round the result of each
2165 operation according to the rules below
2166 * Negative P is ignored in Math::BigInt, since BigInts never have digits
2167 after the decimal point
2168 !* Math::BigFloat uses Math::BigInts internally, but setting A or P inside
2169 ! Math::BigInt as globals should not tamper with the parts of a BigFloat.
2170 ! Thus a flag is used to mark all Math::BigFloat numbers as 'never round'
2174 * It only makes sense that a number has only one of A or P at a time.
2175 Since you can set/get both A and P, there is a rule that will practically
2176 enforce only A or P to be in effect at a time, even if both are set.
2177 This is called precedence.
2178 !* If two objects are involved in an operation, and one of them has A in
2179 ! effect, and the other P, this should result in a warning or an error,
2181 * A takes precendence over P (Hint: A comes before P). If A is defined, it
2182 is used, otherwise P is used. If neither of them is defined, nothing is
2183 used, i.e. the result will have as many digits as it can (with an
2184 exception for fdiv/fsqrt) and will not be rounded.
2185 * There is another setting for fdiv() (and thus for fsqrt()). If neither of
2186 A or P is defined, fdiv() will use a fallback (F) of $div_scale digits.
2187 If either the dividend's or the divisor's mantissa has more digits than
2188 the value of F, the higher value will be used instead of F.
2189 This is to limit the digits (A) of the result (just consider what would
2190 happen with unlimited A and P in the case of 1/3 :-)
2191 * fdiv will calculate 1 more digit than required (determined by
2192 A, P or F), and, if F is not used, round the result
2193 (this will still fail in the case of a result like 0.12345000000001 with A
2194 or P of 5, but this cannot be helped - or can it?)
2195 * Thus you can have the math done by on Math::Big* class in three modes:
2196 + never round (this is the default):
2197 This is done by setting A and P to undef. No math operation
2198 will round the result, with fdiv() and fsqrt() as exceptions to guard
2199 against overflows. You must explicitely call bround(), bfround() or
2200 round() (the latter with parameters).
2201 Note: Once you have rounded a number, the settings will 'stick' on it
2202 and 'infect' all other numbers engaged in math operations with it, since
2203 local settings have the highest precedence. So, to get SaferRound[tm],
2204 use a copy() before rounding like this:
2206 $x = Math::BigFloat->new(12.34);
2207 $y = Math::BigFloat->new(98.76);
2208 $z = $x * $y; # 1218.6984
2209 print $x->copy()->fround(3); # 12.3 (but A is now 3!)
2210 $z = $x * $y; # still 1218.6984, without
2211 # copy would have been 1210!
2213 + round after each op:
2214 After each single operation (except for testing like is_zero()), the
2215 method round() is called and the result is rounded appropriately. By
2216 setting proper values for A and P, you can have all-the-same-A or
2217 all-the-same-P modes. For example, Math::Currency might set A to undef,
2218 and P to -2, globally.
2220 ?Maybe an extra option that forbids local A & P settings would be in order,
2221 ?so that intermediate rounding does not 'poison' further math?
2223 =item Overriding globals
2225 * you will be able to give A, P and R as an argument to all the calculation
2226 routines; the second parameter is A, the third one is P, and the fourth is
2227 R (shift place by one for binary operations like add). P is used only if
2228 the first parameter (A) is undefined. These three parameters override the
2229 globals in the order detailed as follows, i.e. the first defined value
2231 (local: per object, global: global default, parameter: argument to sub)
2234 + local A (if defined on both of the operands: smaller one is taken)
2235 + local P (if defined on both of the operands: smaller one is taken)
2239 * fsqrt() will hand its arguments to fdiv(), as it used to, only now for two
2240 arguments (A and P) instead of one
2242 =item Local settings
2244 * You can set A and P locally by using $x->accuracy() and $x->precision()
2245 and thus force different A and P for different objects/numbers.
2246 * Setting A or P this way immediately rounds $x to the new value.
2250 * the rounding routines will use the respective global or local settings.
2251 fround()/bround() is for accuracy rounding, while ffround()/bfround()
2253 * the two rounding functions take as the second parameter one of the
2254 following rounding modes (R):
2255 'even', 'odd', '+inf', '-inf', 'zero', 'trunc'
2256 * you can set and get the global R by using Math::SomeClass->round_mode()
2257 or by setting $Math::SomeClass::rnd_mode
2258 * after each operation, $result->round() is called, and the result may
2259 eventually be rounded (that is, if A or P were set either locally,
2260 globally or as parameter to the operation)
2261 * to manually round a number, call $x->round($A,$P,$rnd_mode);
2262 this will round the number by using the appropriate rounding function
2263 and then normalize it.
2264 * rounding modifies the local settings of the number:
2266 $x = Math::BigFloat->new(123.456);
2270 Here 4 takes precedence over 5, so 123.5 is the result and $x->accuracy()
2271 will be 4 from now on.
2273 =item Default values
2282 * The defaults are set up so that the new code gives the same results as
2283 the old code (except in a few cases on fdiv):
2284 + Both A and P are undefined and thus will not be used for rounding
2285 after each operation.
2286 + round() is thus a no-op, unless given extra parameters A and P
2292 The actual numbers are stored as unsigned big integers, and math with them is
2293 done (by default) by a module called Math::BigInt::Calc. This is equivalent to:
2295 use Math::BigInt lib => 'calc';
2297 You can change this by using:
2299 use Math::BigInt lib => 'BitVect';
2301 ('Math::BitInt::BitVect' works, too.)
2303 Calc.pm uses as internal format an array of elements of base 100000 digits
2304 with the least significant digit first, BitVect.pm uses a bit vector of base 2,
2305 most significant bit first.
2307 The sign C</^[+-]$/> is stored separately. The string 'NaN' is used to
2308 represent the result when input arguments are not numbers. '+inf' and
2309 '-inf' represent infinity.
2311 You should neither care about nor depend on the internal representation; it
2312 might change without notice. Use only method calls like C<< $x->sign(); >>
2313 instead of relying on the internal hash keys like in C<< $x->{sign}; >>.
2315 =head2 mantissa(), exponent() and parts()
2317 C<mantissa()> and C<exponent()> return the said parts of the BigInt such
2320 $m = $x->mantissa();
2321 $e = $x->exponent();
2322 $y = $m * ( 10 ** $e );
2323 print "ok\n" if $x == $y;
2325 C<< ($m,$e) = $x->parts() >> is just a shortcut that gives you both of them
2326 in one go. Both the returned mantissa and exponent have a sign.
2328 Currently, for BigInts C<$e> will be always 0, except for NaN where it will be
2329 NaN and for $x == 0, then it will be 1 (to be compatible with Math::BigFloat's
2330 internal representation of a zero as C<0E1>).
2332 C<$m> will always be a copy of the original number. The relation between $e
2333 and $m might change in the future, but will always be equivalent in a
2334 numerical sense, e.g. $m might get minimized.
2338 use Math::BigInt qw(bstr bint);
2339 $x = bstr("1234") # string "1234"
2340 $x = "$x"; # same as bstr()
2341 $x = bneg("1234") # Bigint "-1234"
2342 $x = Math::BigInt->bneg("1234"); # Bigint "-1234"
2343 $x = Math::BigInt->babs("-12345"); # Bigint "12345"
2344 $x = Math::BigInt->bnorm("-0 00"); # BigInt "0"
2345 $x = bint(1) + bint(2); # BigInt "3"
2346 $x = bint(1) + "2"; # ditto (auto-BigIntify of "2")
2347 $x = bint(1); # BigInt "1"
2348 $x = $x + 5 / 2; # BigInt "3"
2349 $x = $x ** 3; # BigInt "27"
2350 $x *= 2; # BigInt "54"
2351 $x = new Math::BigInt; # BigInt "0"
2353 $x = Math::BigInt->badd(4,5) # BigInt "9"
2354 $x = Math::BigInt::badd(4,5) # BigInt "9"
2355 print $x->bsstr(); # 9e+0
2357 Examples for rounding:
2362 $x = Math::BigFloat->new(123.4567);
2363 $y = Math::BigFloat->new(123.456789);
2364 $Math::BigFloat::accuracy = 4; # no more A than 4
2366 ok ($x->copy()->fround(),123.4); # even rounding
2367 print $x->copy()->fround(),"\n"; # 123.4
2368 Math::BigFloat->round_mode('odd'); # round to odd
2369 print $x->copy()->fround(),"\n"; # 123.5
2370 $Math::BigFloat::accuracy = 5; # no more A than 5
2371 Math::BigFloat->round_mode('odd'); # round to odd
2372 print $x->copy()->fround(),"\n"; # 123.46
2373 $y = $x->copy()->fround(4),"\n"; # A = 4: 123.4
2374 print "$y, ",$y->accuracy(),"\n"; # 123.4, 4
2376 $Math::BigFloat::accuracy = undef; # A not important
2377 $Math::BigFloat::precision = 2; # P important
2378 print $x->copy()->bnorm(),"\n"; # 123.46
2379 print $x->copy()->fround(),"\n"; # 123.46
2381 =head1 Autocreating constants
2383 After C<use Math::BigInt ':constant'> all the B<integer> decimal constants
2384 in the given scope are converted to C<Math::BigInt>. This conversion
2385 happens at compile time.
2389 perl -MMath::BigInt=:constant -e 'print 2**100,"\n"'
2391 prints the integer value of C<2**100>. Note that without conversion of
2392 constants the expression 2**100 will be calculated as perl scalar.
2394 Please note that strings and floating point constants are not affected,
2397 use Math::BigInt qw/:constant/;
2399 $x = 1234567890123456789012345678901234567890
2400 + 123456789123456789;
2401 $y = '1234567890123456789012345678901234567890'
2402 + '123456789123456789';
2404 do not work. You need an explicit Math::BigInt->new() around one of the
2409 Using the form $x += $y; etc over $x = $x + $y is faster, since a copy of $x
2410 must be made in the second case. For long numbers, the copy can eat up to 20%
2411 of the work (in the case of addition/subtraction, less for
2412 multiplication/division). If $y is very small compared to $x, the form
2413 $x += $y is MUCH faster than $x = $x + $y since making the copy of $x takes
2414 more time then the actual addition.
2416 With a technique called copy-on-write, the cost of copying with overload could
2417 be minimized or even completely avoided. This is currently not implemented.
2419 The new version of this module is slower on new(), bstr() and numify(). Some
2420 operations may be slower for small numbers, but are significantly faster for
2421 big numbers. Other operations are now constant (O(1), like bneg(), babs()
2422 etc), instead of O(N) and thus nearly always take much less time.
2424 For more benchmark results see http://bloodgate.com/perl/benchmarks.html
2426 =head2 Replacing the math library
2428 You can use an alternative library to drive Math::BigInt via:
2430 use Math::BigInt lib => 'Module';
2432 The default is called Math::BigInt::Calc and is a pure-perl base 100,000
2433 math package that consists of the standard routine present in earlier versions
2436 There are also Math::BigInt::Scalar (primarily for testing) and
2437 Math::BigInt::BitVect; these and others can be found via
2438 L<http://search.cpan.org/>:
2440 use Math::BigInt lib => 'BitVect';
2442 my $x = Math::BigInt->new(2);
2443 print $x ** (1024*1024);
2449 =item :constant and eval()
2451 Under Perl prior to 5.6.0 having an C<use Math::BigInt ':constant';> and
2452 C<eval()> in your code will crash with "Out of memory". This is probably an
2453 overload/exporter bug. You can workaround by not having C<eval()>
2454 and ':constant' at the same time or upgrade your Perl.
2460 Some things might not work as you expect them. Below is documented what is
2461 known to be troublesome:
2465 =item stringify, bstr(), bsstr() and 'cmp'
2467 Both stringify and bstr() now drop the leading '+'. The old code would return
2468 '+3', the new returns '3'. This is to be consistent with Perl and to make
2469 cmp (especially with overloading) to work as you expect. It also solves
2470 problems with Test.pm, it's ok() uses 'eq' internally.
2472 Mark said, when asked about to drop the '+' altogether, or make only cmp work:
2474 I agree (with the first alternative), don't add the '+' on positive
2475 numbers. It's not as important anymore with the new internal
2476 form for numbers. It made doing things like abs and neg easier,
2477 but those have to be done differently now anyway.
2479 So, the following examples will now work all as expected:
2482 BEGIN { plan tests => 1 }
2485 my $x = new Math::BigInt 3*3;
2486 my $y = new Math::BigInt 3*3;
2489 print "$x eq 9" if $x eq $y;
2490 print "$x eq 9" if $x eq '9';
2491 print "$x eq 9" if $x eq 3*3;
2493 Additionally, the following still works:
2495 print "$x == 9" if $x == $y;
2496 print "$x == 9" if $x == 9;
2497 print "$x == 9" if $x == 3*3;
2499 There is now a C<bsstr()> method to get the string in scientific notation aka
2500 C<1e+2> instead of C<100>. Be advised that overloaded 'eq' always uses bstr()
2501 for comparisation, but Perl will represent some numbers as 100 and others
2502 as 1e+308. If in doubt, convert both arguments to Math::BigInt before doing eq:
2505 BEGIN { plan tests => 3 }
2508 $x = Math::BigInt->new('1e56'); $y = 1e56;
2509 ok ($x,$y); # will fail
2510 ok ($x->bsstr(),$y); # okay
2511 $y = Math::BigInt->new($y);
2516 C<int()> will return (at least for Perl v5.7.1 and up) another BigInt, not a
2519 $x = Math::BigInt->new(123);
2520 $y = int($x); # BigInt 123
2521 $x = Math::BigFloat->new(123.45);
2522 $y = int($x); # BigInt 123
2524 In all Perl versions you can use C<as_number()> for the same effect:
2526 $x = Math::BigFloat->new(123.45);
2527 $y = $x->as_number(); # BigInt 123
2529 This also works for other subclasses, like Math::String.
2533 The following will probably not do what you expect:
2535 print $c->bdiv(10000),"\n";
2537 It prints both quotient and reminder since print calls C<bdiv()> in list
2538 context. Also, C<bdiv()> will modify $c, so be carefull. You probably want
2541 print $c / 10000,"\n";
2542 print scalar $c->bdiv(10000),"\n"; # or if you want to modify $c
2546 The quotient is always the greatest integer less than or equal to the
2547 real-valued quotient of the two operands, and the remainder (when it is
2548 nonzero) always has the same sign as the second operand; so, for
2556 As a consequence, the behavior of the operator % agrees with the
2557 behavior of Perl's built-in % operator (as documented in the perlop
2558 manpage), and the equation
2560 $x == ($x / $y) * $y + ($x % $y)
2562 holds true for any $x and $y, which justifies calling the two return
2563 values of bdiv() the quotient and remainder.
2565 Perl's 'use integer;' changes the behaviour of % and / for scalars, but will
2566 not change BigInt's way to do things. This is because under 'use integer' Perl
2567 will do what the underlying C thinks is right and this is different for each
2568 system. If you need BigInt's behaving exactly like Perl's 'use integer', bug
2569 the author to implement it ;)
2571 =item Modifying and =
2575 $x = Math::BigFloat->new(5);
2578 It will not do what you think, e.g. making a copy of $x. Instead it just makes
2579 a second reference to the B<same> object and stores it in $y. Thus anything
2580 that modifies $x will modify $y, and vice versa.
2583 print "$x, $y\n"; # prints '10, 10'
2585 If you want a true copy of $x, use:
2589 See also the documentation for overload.pm regarding C<=>.
2593 C<bpow()> (and the rounding functions) now modifies the first argument and
2594 return it, unlike the old code which left it alone and only returned the
2595 result. This is to be consistent with C<badd()> etc. The first three will
2596 modify $x, the last one won't:
2598 print bpow($x,$i),"\n"; # modify $x
2599 print $x->bpow($i),"\n"; # ditto
2600 print $x **= $i,"\n"; # the same
2601 print $x ** $i,"\n"; # leave $x alone
2603 The form C<$x **= $y> is faster than C<$x = $x ** $y;>, though.
2605 =item Overloading -$x
2615 since overload calls C<sub($x,0,1);> instead of C<neg($x)>. The first variant
2616 needs to preserve $x since it does not know that it later will get overwritten.
2617 This makes a copy of $x and takes O(N), but $x->bneg() is O(1).
2619 With Copy-On-Write, this issue will be gone. Stay tuned...
2621 =item Mixing different object types
2623 In Perl you will get a floating point value if you do one of the following:
2629 With overloaded math, only the first two variants will result in a BigFloat:
2634 $mbf = Math::BigFloat->new(5);
2635 $mbi2 = Math::BigInteger->new(5);
2636 $mbi = Math::BigInteger->new(2);
2638 # what actually gets called:
2639 $float = $mbf + $mbi; # $mbf->badd()
2640 $float = $mbf / $mbi; # $mbf->bdiv()
2641 $integer = $mbi + $mbf; # $mbi->badd()
2642 $integer = $mbi2 / $mbi; # $mbi2->bdiv()
2643 $integer = $mbi2 / $mbf; # $mbi2->bdiv()
2645 This is because math with overloaded operators follows the first (dominating)
2646 operand, this one's operation is called and returns thus the result. So,
2647 Math::BigInt::bdiv() will always return a Math::BigInt, regardless whether
2648 the result should be a Math::BigFloat or the second operant is one.
2650 To get a Math::BigFloat you either need to call the operation manually,
2651 make sure the operands are already of the proper type or casted to that type
2652 via Math::BigFloat->new():
2654 $float = Math::BigFloat->new($mbi2) / $mbi; # = 2.5
2656 Beware of simple "casting" the entire expression, this would only convert
2657 the already computed result:
2659 $float = Math::BigFloat->new($mbi2 / $mbi); # = 2.0 thus wrong!
2661 Beware also of the order of more complicated expressions like:
2663 $integer = ($mbi2 + $mbi) / $mbf; # int / float => int
2664 $integer = $mbi2 / Math::BigFloat->new($mbi); # ditto
2666 If in doubt, break the expression into simpler terms, or cast all operands
2667 to the desired resulting type.
2669 Scalar values are a bit different, since:
2674 will both result in the proper type due to the way the overloaded math works.
2676 This section also applies to other overloaded math packages, like Math::String.
2680 C<bsqrt()> works only good if the result is an big integer, e.g. the square
2681 root of 144 is 12, but from 12 the square root is 3, regardless of rounding
2684 If you want a better approximation of the square root, then use:
2686 $x = Math::BigFloat->new(12);
2687 $Math::BigFloat::precision = 0;
2688 Math::BigFloat->round_mode('even');
2689 print $x->copy->bsqrt(),"\n"; # 4
2691 $Math::BigFloat::precision = 2;
2692 print $x->bsqrt(),"\n"; # 3.46
2693 print $x->bsqrt(3),"\n"; # 3.464
2699 This program is free software; you may redistribute it and/or modify it under
2700 the same terms as Perl itself.
2704 L<Math::BigFloat> and L<Math::Big>.
2708 Original code by Mark Biggar, overloaded interface by Ilya Zakharevich.
2709 Completely rewritten by Tels http://bloodgate.com in late 2000, 2001.