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 BigIint 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 op are ref()
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 (array '+', '1')
772 # or -1 if signis 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} !~ /^[+-]$/);
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} !~ /^[+-]$/);
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?)
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 here a bug, -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 represantation:
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 represantion 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 represantation
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 can not 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 "can not 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;
1606 my $c = $CALC; $c =~ s/::/\//g; $c .= '.pm' if $c !~ /\.pm$/;
1612 # internal normalization function that strips leading zeros from the array
1613 # args: ref to array
1616 my $cnt = scalar @$s; # get count of parts
1618 #print "strip: cnt $cnt i $i\n";
1619 # '0', '3', '4', '0', '0',
1624 # => fcnt = cnt - i (5-2 => 3, cnt => 5-1 = 4, throw away from 4th pos)
1625 # >= 1: skip first part (this can be zero)
1626 while ($i > 0) { last if $s->[$i] != 0; $i--; }
1627 $i++; splice @$s,$i if ($i < $cnt); # $i cant be 0
1633 # convert a (ref to) big hex string to BigInt, return undef for error
1636 my $x = Math::BigInt->bzero();
1637 return $x->bnan() if $$hs !~ /^[\-\+]?0x[0-9A-Fa-f]+$/;
1639 my $sign = '+'; $sign = '-' if ($$hs =~ /^\-/);
1641 $$hs =~ s/^[+-]?//; # strip sign
1642 if ($CALC->can('_from_hex'))
1644 $x->{value} = $CALC->_from_hex($hs);
1648 # fallback to pure perl
1649 my $mul = Math::BigInt->bzero(); $mul++;
1650 my $x65536 = Math::BigInt->new(65536);
1651 my $len = CORE::length($$hs)-2;
1652 $len = int($len/4); # 4-digit parts, w/o '0x'
1653 my $val; my $i = -4;
1656 $val = substr($$hs,$i,4);
1657 $val =~ s/^[\-\+]?0x// if $len == 0; # for last part only because
1658 $val = hex($val); # hex does not like wrong chars
1659 # print "$val ",substr($$hs,$i,4),"\n";
1661 $x += $mul * $val if $val != 0;
1662 $mul *= $x65536 if $len >= 0; # skip last mul
1665 $x->{sign} = $sign if !$x->is_zero(); # no '-0'
1671 # convert a (ref to) big binary string to BigInt, return undef for error
1674 my $x = Math::BigInt->bzero();
1675 return $x->bnan() if $$bs !~ /^[\-\+]?0b[01]+$/;
1677 my $mul = Math::BigInt->bzero(); $mul++;
1678 my $x256 = Math::BigInt->new(256);
1680 my $sign = '+'; $sign = '-' if ($$bs =~ /^\-/);
1681 $$bs =~ s/^[+-]?//; # strip sign
1682 if ($CALC->can('_from_bin'))
1684 $x->{value} = $CALC->_from_bin($bs);
1688 my $len = CORE::length($$bs)-2;
1689 $len = int($len/8); # 8-digit parts, w/o '0b'
1690 my $val; my $i = -8;
1693 $val = substr($$bs,$i,8);
1694 $val =~ s/^[\-\+]?0b// if $len == 0; # for last part only
1695 #$val = oct('0b'.$val); # does not work on Perl prior 5.6.0
1696 $val = ('0' x (8-CORE::length($val))).$val if CORE::length($val) < 8;
1697 $val = ord(pack('B8',$val));
1698 # print "$val ",substr($$bs,$i,16),"\n";
1700 $x += $mul * $val if $val != 0;
1701 $mul *= $x256 if $len >= 0; # skip last mul
1704 $x->{sign} = $sign if !$x->is_zero();
1710 # (ref to num_str) return num_str
1711 # internal, take apart a string and return the pieces
1715 $$x =~ s/^\s+//g; # strip white space at front
1716 $$x =~ s/\s+$//g; # strip white space at end
1717 #$$x =~ s/\s+//g; # strip white space (no longer)
1718 return if $$x eq "";
1720 return _from_hex($x) if $$x =~ /^[\-\+]?0x/; # hex string
1721 return _from_bin($x) if $$x =~ /^[\-\+]?0b/; # binary string
1723 return if $$x !~ /^[\-\+]?\.?[0-9]/;
1725 $$x =~ s/(\d)_(\d)/$1$2/g; # strip underscores between digits
1726 $$x =~ s/(\d)_(\d)/$1$2/g; # do twice for 1_2_3
1728 # some possible inputs:
1729 # 2.1234 # 0.12 # 1 # 1E1 # 2.134E1 # 434E-10 # 1.02009E-2
1730 # .2 # 1_2_3.4_5_6 # 1.4E1_2_3 # 1e3 # +.2
1732 #print "input: '$$x' ";
1733 my ($m,$e) = split /[Ee]/,$$x;
1734 $e = '0' if !defined $e || $e eq "";
1735 # print "m '$m' e '$e'\n";
1736 # sign,value for exponent,mantint,mantfrac
1737 my ($es,$ev,$mis,$miv,$mfv);
1739 if ($e =~ /^([+-]?)0*(\d+)$/) # strip leading zeros
1742 #print "'$m' '$e' e: $es $ev ";
1744 return if $m eq '.' || $m eq '';
1745 my ($mi,$mf) = split /\./,$m;
1746 $mi = '0' if !defined $mi;
1747 $mi .= '0' if $mi =~ /^[\-\+]?$/;
1748 $mf = '0' if !defined $mf || $mf eq '';
1749 if ($mi =~ /^([+-]?)0*(\d+)$/) # strip leading zeros
1751 $mis = $1||'+'; $miv = $2;
1752 # print "$mis $miv";
1753 # valid, existing fraction part of mantissa?
1754 return unless ($mf =~ /^(\d*?)0*$/); # strip trailing zeros
1756 #print " split: $mis $miv . $mfv E $es $ev\n";
1757 return (\$mis,\$miv,\$mfv,\$es,\$ev);
1760 return; # NaN, not a number
1765 # an object might be asked to return itself as bigint on certain overloaded
1766 # operations, this does exactly this, so that sub classes can simple inherit
1767 # it or override with their own integer conversion routine
1770 return $self->copy();
1773 ##############################################################################
1774 # internal calculation routines (others are in Math::BigInt::Calc etc)
1778 # post-normalized compare for internal use (honors signs)
1779 # input: ref to value, ref to value, sign, sign
1781 my ($cx,$cy,$sx,$sy) = @_;
1785 return 1 if $sy eq '-'; # 0 check handled above
1786 #return acmp($cx,$cy);
1787 return $CALC->_acmp($cx,$cy);
1792 return -1 if $sy eq '+';
1793 #return acmp($cy,$cx);
1794 return $CALC->_acmp($cy,$cx);
1801 # (BINT or num_str, BINT or num_str) return BINT
1802 # does modify first argument
1805 my $x = shift; my $ty = shift;
1806 return $x->bnan() if ($x->{sign} eq $nan) || ($ty->{sign} eq $nan);
1807 return $x * $ty / bgcd($x,$ty);
1812 # (BINT or num_str, BINT or num_str) return BINT
1813 # does modify first arg
1814 # GCD -- Euclids algorithm E, Knuth Vol 2 pg 296
1816 my $x = shift; my $ty = $class->new(shift); # preserve y, but make class
1817 return $x->bnan() if $x->{sign} !~ /^[+-]$/ || $ty->{sign} !~ /^[+-]$/;
1819 while (!$ty->is_zero())
1821 ($x, $ty) = ($ty,bmod($x,$ty));
1826 ###############################################################################
1827 # this method return 0 if the object can be modified, or 1 for not
1828 # We use a fast use constant statement here, to avoid costly calls. Subclasses
1829 # may override it with special code (f.i. Math::BigInt::Constant does so)
1831 sub modify () { 0; }
1838 Math::BigInt - Arbitrary size integer math package
1845 $x = Math::BigInt->new($str); # defaults to 0
1846 $nan = Math::BigInt->bnan(); # create a NotANumber
1847 $zero = Math::BigInt->bzero();# create a "+0"
1850 $x->is_zero(); # return whether arg is zero or not
1851 $x->is_nan(); # return whether arg is NaN or not
1852 $x->is_one(); # true if arg is +1
1853 $x->is_one('-'); # true if arg is -1
1854 $x->is_odd(); # true if odd, false for even
1855 $x->is_even(); # true if even, false for odd
1856 $x->is_positive(); # true if >= 0
1857 $x->is_negative(); # true if < 0
1858 $x->is_inf(sign); # true if +inf, or -inf (sign is default '+')
1860 $x->bcmp($y); # compare numbers (undef,<0,=0,>0)
1861 $x->bacmp($y); # compare absolutely (undef,<0,=0,>0)
1862 $x->sign(); # return the sign, either +,- or NaN
1863 $x->digit($n); # return the nth digit, counting from right
1864 $x->digit(-$n); # return the nth digit, counting from left
1866 # The following all modify their first argument:
1869 $x->bzero(); # set $x to 0
1870 $x->bnan(); # set $x to NaN
1872 $x->bneg(); # negation
1873 $x->babs(); # absolute value
1874 $x->bnorm(); # normalize (no-op)
1875 $x->bnot(); # two's complement (bit wise not)
1876 $x->binc(); # increment x by 1
1877 $x->bdec(); # decrement x by 1
1879 $x->badd($y); # addition (add $y to $x)
1880 $x->bsub($y); # subtraction (subtract $y from $x)
1881 $x->bmul($y); # multiplication (multiply $x by $y)
1882 $x->bdiv($y); # divide, set $x to quotient
1883 # return (quo,rem) or quo if scalar
1885 $x->bmod($y); # modulus (x % y)
1886 $x->bpow($y); # power of arguments (x ** y)
1887 $x->blsft($y); # left shift
1888 $x->brsft($y); # right shift
1889 $x->blsft($y,$n); # left shift, by base $n (like 10)
1890 $x->brsft($y,$n); # right shift, by base $n (like 10)
1892 $x->band($y); # bitwise and
1893 $x->bior($y); # bitwise inclusive or
1894 $x->bxor($y); # bitwise exclusive or
1895 $x->bnot(); # bitwise not (two's complement)
1897 $x->bsqrt(); # calculate square-root
1899 $x->round($A,$P,$round_mode); # round to accuracy or precision using mode $r
1900 $x->bround($N); # accuracy: preserve $N digits
1901 $x->bfround($N); # round to $Nth digit, no-op for BigInts
1903 # The following do not modify their arguments in BigInt, but do in BigFloat:
1904 $x->bfloor(); # return integer less or equal than $x
1905 $x->bceil(); # return integer greater or equal than $x
1907 # The following do not modify their arguments:
1909 bgcd(@values); # greatest common divisor
1910 blcm(@values); # lowest common multiplicator
1912 $x->bstr(); # normalized string
1913 $x->bsstr(); # normalized string in scientific notation
1914 $x->length(); # return number of digits in number
1915 ($x,$f) = $x->length(); # length of number and length of fraction part
1917 $x->exponent(); # return exponent as BigInt
1918 $x->mantissa(); # return mantissa as BigInt
1919 $x->parts(); # return (mantissa,exponent) as BigInt
1920 $x->copy(); # make a true copy of $x (unlike $y = $x;)
1921 $x->as_number(); # return as BigInt (in BigInt: same as copy())
1925 All operators (inlcuding basic math operations) are overloaded if you
1926 declare your big integers as
1928 $i = new Math::BigInt '123_456_789_123_456_789';
1930 Operations with overloaded operators preserve the arguments which is
1931 exactly what you expect.
1935 =item Canonical notation
1937 Big integer values are strings of the form C</^[+-]\d+$/> with leading
1940 '-0' canonical value '-0', normalized '0'
1941 ' -123_123_123' canonical value '-123123123'
1942 '1_23_456_7890' canonical value '1234567890'
1946 Input values to these routines may be either Math::BigInt objects or
1947 strings of the form C</^\s*[+-]?[\d]+\.?[\d]*E?[+-]?[\d]*$/>.
1949 You can include one underscore between any two digits.
1951 This means integer values like 1.01E2 or even 1000E-2 are also accepted.
1952 Non integer values result in NaN.
1954 Math::BigInt::new() defaults to 0, while Math::BigInt::new('') results
1957 bnorm() on a BigInt object is now effectively a no-op, since the numbers
1958 are always stored in normalized form. On a string, it creates a BigInt
1963 Output values are BigInt objects (normalized), except for bstr(), which
1964 returns a string in normalized form.
1965 Some routines (C<is_odd()>, C<is_even()>, C<is_zero()>, C<is_one()>,
1966 C<is_nan()>) return true or false, while others (C<bcmp()>, C<bacmp()>)
1967 return either undef, <0, 0 or >0 and are suited for sort.
1971 =head1 ACCURACY and PRECISION
1973 Since version v1.33 Math::BigInt and Math::BigFloat do have full support for
1974 accuracy and precision based rounding, both automatically after every
1975 operation as manual.
1977 This section describes the accuracy/precision handling in Math::Big* as it
1978 used to be and is now, completed with an explanation of all terms and
1981 Not yet implemented things (but with correct description) are marked with '!',
1982 things that need to be answered are marked with '?'.
1984 In the next paragraph follows a short description of terms used here (because
1985 these may differ from terms used by others people or documentations).
1987 During the rest of this document the shortcuts A (for accuracy), P (for
1988 precision), F (fallback) and R (rounding mode) will be used.
1992 A fixed number of digits before (positive) or after (negative)
1993 the dot. F.i. 123.45 has a precision of -2. 0 means an integer like 123
1994 (or 120). A precision of 2 means two digits left of the dot are zero, so
1995 123 with P = 1 becomes 120. Note that numbers with zeros before the dot may
1996 have different precisions, because 1200 can have p = 0, 1 or 2 (depending
1997 on what the inital value was). It could also have p < 0, when the digits
1998 after the dot are zero.
2000 !The string output of such a number should be padded with zeros:
2002 ! Initial value P Result String
2003 ! 1234.01 -3 1000 1000
2005 ! 1234.5 -1 1230 1230
2006 ! 1234.001 1 1234 1234.0
2007 ! 1234.01 0 1234 1234
2008 ! 1234.01 2 1234.01 1234.01
2009 ! 1234.01 5 1234.01 1234.01000
2013 Number of significant digits. Leading zeros are not counted. A
2014 number may have an accuracy greater than the non-zero digits
2015 when there are zeros in it or trailing zeros. F.i. 123.456 has A of 6,
2016 10203 has 5, 123.0506 has 7, 123.450000 has 8, and 0.000123 has 3.
2020 When both A and P are undefined, this is used as a fallback accuracy.
2022 =head2 Rounding mode R
2024 When rounding a number, different 'styles' or 'kinds'
2025 of rounding are possible. (Note that random rounding, as in
2026 Math::Round, is not implemented.)
2032 truncation invariably removes all digits following the
2033 rounding place, replacing them with zeros. Thus, 987.65 rounded
2034 to tenths (P=1) becomes 980, and rounded to the fourth sigdig
2035 becomes 987.6 (A=4). 123.456 rounded to the second place after the
2036 dot (P=-2) becomes 123.46.
2038 All other implemented styles of rounding attempt to round to the
2039 "nearest digit." If the digit D immediately to the right of the
2040 rounding place (skipping the decimal point) is greater than 5, the
2041 number is incremented at the rounding place (possibly causing a
2042 cascade of incrementation): e.g. when rounding to units, 0.9 rounds
2043 to 1, and -19.9 rounds to -20. If D < 5, the number is similarly
2044 truncated at the rounding place: e.g. when rounding to units, 0.4
2045 rounds to 0, and -19.4 rounds to -19.
2047 However the results of other styles of rounding differ if the
2048 digit immediately to the right of the rounding place (skipping the
2049 decimal point) is 5 and if there are no digits, or no digits other
2050 than 0, after that 5. In such cases:
2054 rounds the digit at the rounding place to 0, 2, 4, 6, or 8
2055 if it is not already. E.g., when rounding to the first sigdig, 0.45
2056 becomes 0.4, -0.55 becomes -0.6, but 0.4501 becomes 0.5.
2060 rounds the digit at the rounding place to 1, 3, 5, 7, or 9 if
2061 it is not already. E.g., when rounding to the first sigdig, 0.45
2062 becomes 0.5, -0.55 becomes -0.5, but 0.5501 becomes 0.6.
2066 round to plus infinity, i.e. always round up. E.g., when
2067 rounding to the first sigdig, 0.45 becomes 0.5, -0.55 becomes -0.5,
2068 but 0.4501 becomes 0.5.
2072 round to minus infinity, i.e. always round down. E.g., when
2073 rounding to the first sigdig, 0.45 becomes 0.4, -0.55 becomes -0.6,
2074 but 0.4501 becomes 0.5.
2078 round to zero, i.e. positive numbers down, negative ones up.
2079 E.g., when rounding to the first sigdig, 0.45 becomes 0.4, -0.55
2080 becomes -0.5, but 0.4501 becomes 0.5.
2084 The handling of A & P in MBI/MBF (the old core code shipped with Perl
2085 versions <= 5.7.2) is like this:
2091 * ffround($p) is able to round to $p number of digits after the dot
2092 * otherwise P is unused
2094 =item Accuracy (significant digits)
2096 * fround($a) rounds to $a significant digits
2097 * only fdiv() and fsqrt() take A as (optional) paramater
2098 + other operations simple create the same amount (fneg etc), or more (fmul)
2100 + rounding/truncating is only done when explicitly calling one of fround
2101 or ffround, and never for BigInt (not implemented)
2102 * fsqrt() simple hands it's accuracy argument over to fdiv.
2103 * the documentation and the comment in the code indicate two different ways
2104 on how fdiv() determines the maximum number of digits it should calculate,
2105 and the actual code does yet another thing
2107 max($Math::BigFloat::div_scale,length(dividend)+length(divisor))
2109 result has at most max(scale, length(dividend), length(divisor)) digits
2111 scale = max(scale, length(dividend)-1,length(divisor)-1);
2112 scale += length(divisior) - length(dividend);
2113 So for lx =3, ly = 9, scale = 10, scale will be actually 16 (10+9-3).
2114 Actually, the 'difference' added to the scale is calculated from the
2115 number of "significant digits" in dividend and divisor, which is derived
2116 by looking at the length of the mantissa. Which is wrong, since it includes
2117 the + sign (oups) and actually gets 2 for '+100' and 4 for '+101'. Oups
2118 again. Thus 124/3 with div_scale=1 will get you '41.3' based on the strange
2119 assumption that 124 has 3 significant digits, while 120/7 will get you
2120 '17', not '17.1' since 120 is thought to have 2 significant digits.
2121 The rounding after the division then uses the reminder and $y to determine
2122 wether it must round up or down.
2123 ? I have no idea which is the right way. Thats why I used scheme a bit more
2124 ? simple and tweaked the few failing the testcases to match it.
2128 This is how it works now:
2132 =item Setting/Accessing
2134 * You can set the A global via $Math::BigInt::accuracy or
2135 $Math::BigFloat::accuracy or whatever class you are using.
2136 * You can also set P globally by using $Math::SomeClass::precision likewise.
2137 * Globals are classwide, and not inherited by subclasses.
2138 * to undefine A, use $Math::SomeCLass::accuracy = undef
2139 * to undefine P, use $Math::SomeClass::precision = undef
2140 * To be valid, A must be > 0, P can have any value.
2141 * If P is negative, this means round to the P's place right of the dot,
2142 positive values mean left from the dot. P of 0 means round to integer.
2143 * to find out the current global A, take $Math::SomeClass::accuracy
2144 * use $x->accuracy() for the local setting of $x.
2145 * to find out the current global P, take $Math::SomeClass::precision
2146 * use $x->precision() for the local setting
2148 =item Creating numbers
2150 !* When you create a number, there should be a way to define it's A & P
2151 * When a number without specific A or P is created, but the globals are
2152 defined, these should be used to round the number immidiately and also
2153 stored locally at the number. Thus changing the global defaults later on
2154 will not change the A or P of previously created numbers (aka A and P of
2155 $x will be what was in effect when $x was created)
2159 * If A or P are enabled/defined, the are used to round the result of each
2160 operation according to the rules below
2161 * Negative P are ignored in Math::BigInt, since it never has digits after
2163 !* Since Math::BigFloat uses Math::BigInts internally, setting A or P inside
2164 ! Math::BigInt as globals should not hamper with the parts of a BigFloat.
2165 ! Thus a flag is used to mark all Math::BigFloat numbers as 'do never round'
2169 * It makes only sense that a number has only A or P at a time. Since you can
2170 set/get both A and P, there is a rule that will practically enforce only
2171 A or P to be in effect at a time, even if both are set. This is called
2173 !* If two objects are engaged in an operation, and one of them has A in
2174 ! effect, and the other P, this should result in a warning or an error,
2176 * A takes precendence over P (Hint: A comes before P). If A is defined, it
2177 is used, otherwise P is used. If none of them is defined, nothing is used,
2178 e.g. the result will have as many digits as it can (with an exception
2179 for fdiv/fsqrt) and will not be rounded.
2180 * There is another setting for fdiv() (and thus for fsqrt()). If none of A
2181 or P are defined, fdiv() will use a fallback (F) of $div_scale digits.
2182 If either the dividend or the divisors mantissa have more digits than the
2183 F, the higher value will be used instead as F.
2184 This is to limit the digits (A) of the result (just think if what happens
2185 with unlimited A and P in case of 1/3 :-)
2186 * fdiv will calculate 1 more digits than required (determined by
2187 A, P or F), and, if F is not used, round the result
2188 (this will still fail in case of a result like 0.12345000000001 with A
2189 or P of 5, but this can not be helped - or can it?)
2190 * Thus you can have the math done by on Math::Big* class in three modi:
2191 + never round (this is the default):
2192 This is done by setting A and P to undef. No math operation
2193 will round the result, with fdiv() and fsqrt() as exception to guard
2194 against overflows. You must explicitely call bround(), bfround() or
2195 round() (the latter with with parameters).
2196 Note: Once you rounded a number, the settings will 'stick' on it and
2197 'infect' all other numbers engaged in math operations with it, since
2198 local settings have the highest precedence. So, to get SaferRound[tm],
2199 use a copy() before rounding like this:
2201 $x = Math::BigFloat->new(12.34);
2202 $y = Math::BigFloat->new(98.76);
2203 $z = $x * $y; # 1218.6984
2204 print $x->copy()->fround(3); # 12.3 (but A is now 3!)
2205 $z = $x * $y; # still 1218.6984, without
2206 # copy would have been 1210!
2208 + round after each op:
2209 After each single operation (except for testing like is_zero()) the
2210 method round() is called and the result appropriately rounded. By
2211 setting proper values for A and P, you can have all-the-same-A or
2212 all-the-same-P modi. F.i. Math::Current might set A to undef, and P
2215 ?Maybe an extra option, that forbids local A & P settings would be in order,
2216 ?so that intermidiate rounding does not 'poison' further math?
2218 =item Overriding globals
2220 * you will be able to give A, P and R as an argument to all the calculation
2221 routines, the second parameter is A, the third one is P, and the fourth is
2222 R (shift place by one for binary operations like add). P is used only if
2223 the first one (A) is undefined. These three parameters override the
2224 globals in the order detailed as follows, aka the first defined value
2226 (local: per object, global: globally default, parameter: argument to sub)
2229 + local A (if defined on both of the operands: smaller one is taken)
2230 + local P (if defined on both of the operands: smaller one is taken)
2234 * fsqrt() will hand it's arguments to fdiv(), as it used to, only now for two
2235 arguments (A and P) instead of one
2237 =item Local settings
2239 * You can set A and P locally by using $x->accuracy() and $x->precision()
2240 and thus force different A and P for different objects/numbers.
2241 * Setting A or P this way immidiately rounds $x to the new value.
2245 * the rounding routines will use the respective global or local settings
2246 fround()/bround() is for accuracy rounding, while ffround()/bfround()
2248 * the two rounding functions take as the second parameter one of the
2249 following rounding modes (R):
2250 'even', 'odd', '+inf', '-inf', 'zero', 'trunc'
2251 * you can set and get the global R by using Math::SomeClass->round_mode()
2252 or by setting $Math::SomeClass::rnd_mode
2253 * after each operation, $result->round() is called, and the result may
2254 eventually be rounded (that is, if A or P were set either local, global
2255 or as parameter to the operation)
2256 * to manually round a number, call $x->round($A,$P,$rnd_mode);
2257 This will round the number by using the appropriate rounding function
2258 and then normalize it.
2259 * rounding does modify the local settings of the number, so that
2261 $x = Math::BigFloat->new(123.456);
2265 Here 4 takes precedence over 5, so 123.5 is the result and $x->accuracy()
2266 will be 4 from now on.
2268 =item Default values
2277 * The defaults are set up so that the new code gives the same results as
2278 the old code (except in a few cases on fdiv):
2279 + Both A and P are undefined and thus will not be used for rounding
2280 after each operation.
2281 + round() is thus a no-op, unless given extra parameters A and P
2287 The actual numbers are stored as unsigned big integers, and math with them
2288 done (by default) by a module called Math::BigInt::Calc. This is equivalent to:
2290 use Math::BigInt lib => 'calc';
2292 You can change this by using:
2294 use Math::BigInt lib => 'BitVect';
2296 ('Math::BitInt::BitVect' works, too.)
2298 Calc.pm uses as internal format an array of elements of base 100000 digits
2299 with the least significant digit first, BitVect.pm uses a bit vector of base 2,
2300 most significant bit first.
2302 The sign C</^[+-]$/> is stored separately. The string 'NaN' is used to
2303 represent the result when input arguments are not numbers, as well as
2304 the result of dividing by zero. '+inf' or '-inf' represent infinity.
2306 You sould neither care nor depend on the internal representation, it might
2307 change without notice. Use only method calls like C<< $x->sign(); >> instead
2308 relying on the internal hash keys like in C<< $x->{sign}; >>.
2310 =head2 mantissa(), exponent() and parts()
2312 C<mantissa()> and C<exponent()> return the said parts of the BigInt such
2315 $m = $x->mantissa();
2316 $e = $x->exponent();
2317 $y = $m * ( 10 ** $e );
2318 print "ok\n" if $x == $y;
2320 C<($m,$e) = $x->parts()> is just a shortcut that gives you both of them in one
2321 go. Both the returned mantissa and exponent do have a sign.
2323 Currently, for BigInts C<$e> will be always 0, except for NaN where it will be
2324 NaN and for $x == 0, then it will be 1 (to be compatible with Math::BigFlaot's
2325 internal representation of a zero as C<0E1>).
2327 C<$m> will always be a copy of the original number. The relation between $e
2328 and $m might change in the future, but will be always equivalent in a
2329 numerical sense, e.g. $m might get minimized.
2333 use Math::BigInt qw(bstr bint);
2334 $x = bstr("1234") # string "1234"
2335 $x = "$x"; # same as bstr()
2336 $x = bneg("1234") # Bigint "-1234"
2337 $x = Math::BigInt->bneg("1234"); # Bigint "-1234"
2338 $x = Math::BigInt->babs("-12345"); # Bigint "12345"
2339 $x = Math::BigInt->bnorm("-0 00"); # BigInt "0"
2340 $x = bint(1) + bint(2); # BigInt "3"
2341 $x = bint(1) + "2"; # ditto (auto-BigIntify of "2")
2342 $x = bint(1); # BigInt "1"
2343 $x = $x + 5 / 2; # BigInt "3"
2344 $x = $x ** 3; # BigInt "27"
2345 $x *= 2; # BigInt "54"
2346 $x = new Math::BigInt; # BigInt "0"
2348 $x = Math::BigInt->badd(4,5) # BigInt "9"
2349 $x = Math::BigInt::badd(4,5) # BigInt "9"
2350 print $x->bsstr(); # 9e+0
2352 Examples for rounding:
2357 $x = Math::BigFloat->new(123.4567);
2358 $y = Math::BigFloat->new(123.456789);
2359 $Math::BigFloat::accuracy = 4; # no more A than 4
2361 ok ($x->copy()->fround(),123.4); # even rounding
2362 print $x->copy()->fround(),"\n"; # 123.4
2363 Math::BigFloat->round_mode('odd'); # round to odd
2364 print $x->copy()->fround(),"\n"; # 123.5
2365 $Math::BigFloat::accuracy = 5; # no more A than 5
2366 Math::BigFloat->round_mode('odd'); # round to odd
2367 print $x->copy()->fround(),"\n"; # 123.46
2368 $y = $x->copy()->fround(4),"\n"; # A = 4: 123.4
2369 print "$y, ",$y->accuracy(),"\n"; # 123.4, 4
2371 $Math::BigFloat::accuracy = undef; # A not important
2372 $Math::BigFloat::precision = 2; # P important
2373 print $x->copy()->bnorm(),"\n"; # 123.46
2374 print $x->copy()->fround(),"\n"; # 123.46
2376 =head1 Autocreating constants
2378 After C<use Math::BigInt ':constant'> all the B<integer> decimal constants
2379 in the given scope are converted to C<Math::BigInt>. This conversion
2380 happens at compile time.
2384 perl -MMath::BigInt=:constant -e 'print 2**100,"\n"'
2386 prints the integer value of C<2**100>. Note that without conversion of
2387 constants the expression 2**100 will be calculated as perl scalar.
2389 Please note that strings and floating point constants are not affected,
2392 use Math::BigInt qw/:constant/;
2394 $x = 1234567890123456789012345678901234567890
2395 + 123456789123456789;
2396 $x = '1234567890123456789012345678901234567890'
2397 + '123456789123456789';
2399 do both not work. You need a explicit Math::BigInt->new() around one of them.
2403 Using the form $x += $y; etc over $x = $x + $y is faster, since a copy of $x
2404 must be made in the second case. For long numbers, the copy can eat up to 20%
2405 of the work (in case of addition/subtraction, less for
2406 multiplication/division). If $y is very small compared to $x, the form
2407 $x += $y is MUCH faster than $x = $x + $y since making the copy of $x takes
2408 more time then the actual addition.
2410 With a technic called copy-on-write the cost of copying with overload could
2411 be minimized or even completely avoided. This is currently not implemented.
2413 The new version of this module is slower on new(), bstr() and numify(). Some
2414 operations may be slower for small numbers, but are significantly faster for
2415 big numbers. Other operations are now constant (O(1), like bneg(), babs()
2416 etc), instead of O(N) and thus nearly always take much less time.
2418 For more benchmark results see http://bloodgate.com/perl/benchmarks.html
2420 =head2 Replacing the math library
2422 You can use an alternative library to drive Math::BigInt via:
2424 use Math::BigInt lib => 'Module';
2426 The default is called Math::BigInt::Calc and is a pure-perl base 100,000
2427 math package that consist of the standard routine present in earlier versions
2430 There are also Math::BigInt::Scalar (primarily for testing) and
2431 Math::BigInt::BitVect, these and others can be found via
2432 L<http://search.cpan.org/>:
2434 use Math::BigInt lib => 'BitVect';
2436 my $x = Math::BigInt->new(2);
2437 print $x ** (1024*1024);
2443 =item :constant and eval()
2445 Under Perl prior to 5.6.0 having an C<use Math::BigInt ':constant';> and
2446 C<eval()> in your code will crash with "Out of memory". This is probably an
2447 overload/exporter bug. You can workaround by not having C<eval()>
2448 and ':constant' at the same time or upgrade your Perl.
2454 Some things might not work as you expect them. Below is documented what is
2455 known to be troublesome:
2459 =item stringify, bstr(), bsstr() and 'cmp'
2461 Both stringify and bstr() now drop the leading '+'. The old code would return
2462 '+3', the new returns '3'. This is to be consistent with Perl and to make
2463 cmp (especially with overloading) to work as you expect. It also solves
2464 problems with Test.pm, it's ok() uses 'eq' internally.
2466 Mark said, when asked about to drop the '+' altogether, or make only cmp work:
2468 I agree (with the first alternative), don't add the '+' on positive
2469 numbers. It's not as important anymore with the new internal
2470 form for numbers. It made doing things like abs and neg easier,
2471 but those have to be done differently now anyway.
2473 So, the following examples will now work all as expected:
2476 BEGIN { plan tests => 1 }
2479 my $x = new Math::BigInt 3*3;
2480 my $y = new Math::BigInt 3*3;
2483 print "$x eq 9" if $x eq $y;
2484 print "$x eq 9" if $x eq '9';
2485 print "$x eq 9" if $x eq 3*3;
2487 Additionally, the following still works:
2489 print "$x == 9" if $x == $y;
2490 print "$x == 9" if $x == 9;
2491 print "$x == 9" if $x == 3*3;
2493 There is now a C<bsstr()> method to get the string in scientific notation aka
2494 C<1e+2> instead of C<100>. Be advised that overloaded 'eq' always uses bstr()
2495 for comparisation, but Perl will represent some numbers as 100 and others
2496 as 1e+308. If in doubt, convert both arguments to Math::BigInt before doing eq:
2499 BEGIN { plan tests => 3 }
2502 $x = Math::BigInt->new('1e56'); $y = 1e56;
2503 ok ($x,$y); # will fail
2504 ok ($x->bsstr(),$y); # okay
2505 $y = Math::BigInt->new($y);
2510 C<int()> will return (at least for Perl v5.7.1 and up) another BigInt, not a
2513 $x = Math::BigInt->new(123);
2514 $y = int($x); # BigInt 123
2515 $x = Math::BigFloat->new(123.45);
2516 $y = int($x); # BigInt 123
2518 In all Perl versions you can use C<as_number()> for the same effect:
2520 $x = Math::BigFloat->new(123.45);
2521 $y = $x->as_number(); # BigInt 123
2523 This also works for other subclasses, like Math::String.
2527 The following will probably not do what you expect:
2529 print $c->bdiv(10000),"\n";
2531 It prints both quotient and reminder since print calls C<bdiv()> in list
2532 context. Also, C<bdiv()> will modify $c, so be carefull. You probably want
2535 print $c / 10000,"\n";
2536 print scalar $c->bdiv(10000),"\n"; # or if you want to modify $c
2540 The quotient is always the greatest integer less than or equal to the
2541 real-valued quotient of the two operands, and the remainder (when it is
2542 nonzero) always has the same sign as the second operand; so, for
2550 As a consequence, the behavior of the operator % agrees with the
2551 behavior of Perl's built-in % operator (as documented in the perlop
2552 manpage), and the equation
2554 $x == ($x / $y) * $y + ($x % $y)
2556 holds true for any $x and $y, which justifies calling the two return
2557 values of bdiv() the quotient and remainder.
2559 Perl's 'use integer;' changes the behaviour of % and / for scalars, but will
2560 not change BigInt's way to do things. This is because under 'use integer' Perl
2561 will do what the underlying C thinks is right and this is different for each
2562 system. If you need BigInt's behaving exactly like Perl's 'use integer', bug
2563 the author to implement it ;)
2565 =item Modifying and =
2569 $x = Math::BigFloat->new(5);
2572 It will not do what you think, e.g. making a copy of $x. Instead it just makes
2573 a second reference to the B<same> object and stores it in $y. Thus anything
2574 that modifies $x will modify $y, and vice versa.
2577 print "$x, $y\n"; # prints '10, 10'
2579 If you want a true copy of $x, use:
2583 See also the documentation in for overload.pm regarding C<=>.
2587 C<bpow()> (and the rounding functions) now modifies the first argument and
2588 return it, unlike the old code which left it alone and only returned the
2589 result. This is to be consistent with C<badd()> etc. The first three will
2590 modify $x, the last one won't:
2592 print bpow($x,$i),"\n"; # modify $x
2593 print $x->bpow($i),"\n"; # ditto
2594 print $x **= $i,"\n"; # the same
2595 print $x ** $i,"\n"; # leave $x alone
2597 The form C<$x **= $y> is faster than C<$x = $x ** $y;>, though.
2599 =item Overloading -$x
2609 since overload calls C<sub($x,0,1);> instead of C<neg($x)>. The first variant
2610 needs to preserve $x since it does not know that it later will get overwritten.
2611 This makes a copy of $x and takes O(N), but $x->bneg() is O(1).
2613 With Copy-On-Write, this issue will be gone. Stay tuned...
2615 =item Mixing different object types
2617 In Perl you will get a floating point value if you do one of the following:
2623 With overloaded math, only the first two variants will result in a BigFloat:
2628 $mbf = Math::BigFloat->new(5);
2629 $mbi2 = Math::BigInteger->new(5);
2630 $mbi = Math::BigInteger->new(2);
2632 # what actually gets called:
2633 $float = $mbf + $mbi; # $mbf->badd()
2634 $float = $mbf / $mbi; # $mbf->bdiv()
2635 $integer = $mbi + $mbf; # $mbi->badd()
2636 $integer = $mbi2 / $mbi; # $mbi2->bdiv()
2637 $integer = $mbi2 / $mbf; # $mbi2->bdiv()
2639 This is because math with overloaded operators follows the first (dominating)
2640 operand, this one's operation is called and returns thus the result. So,
2641 Math::BigInt::bdiv() will always return a Math::BigInt, regardless whether
2642 the result should be a Math::BigFloat or the second operant is one.
2644 To get a Math::BigFloat you either need to call the operation manually,
2645 make sure the operands are already of the proper type or casted to that type
2646 via Math::BigFloat->new():
2648 $float = Math::BigFloat->new($mbi2) / $mbi; # = 2.5
2650 Beware of simple "casting" the entire expression, this would only convert
2651 the already computed result:
2653 $float = Math::BigFloat->new($mbi2 / $mbi); # = 2.0 thus wrong!
2655 Beware also of the order of more complicated expressions like:
2657 $integer = ($mbi2 + $mbi) / $mbf; # int / float => int
2658 $integer = $mbi2 / Math::BigFloat->new($mbi); # ditto
2660 If in doubt, break the expression into simpler terms, or cast all operands
2661 to the desired resulting type.
2663 Scalar values are a bit different, since:
2668 will both result in the proper type due to the way the overloaded math works.
2670 This section also applies to other overloaded math packages, like Math::String.
2674 C<bsqrt()> works only good if the result is an big integer, e.g. the square
2675 root of 144 is 12, but from 12 the square root is 3, regardless of rounding
2678 If you want a better approximation of the square root, then use:
2680 $x = Math::BigFloat->new(12);
2681 $Math::BigFloat::precision = 0;
2682 Math::BigFloat->round_mode('even');
2683 print $x->copy->bsqrt(),"\n"; # 4
2685 $Math::BigFloat::precision = 2;
2686 print $x->bsqrt(),"\n"; # 3.46
2687 print $x->bsqrt(3),"\n"; # 3.464
2693 This program is free software; you may redistribute it and/or modify it under
2694 the same terms as Perl itself.
2698 L<Math::BigFloat> and L<Math::Big>.
2702 Original code by Mark Biggar, overloaded interface by Ilya Zakharevich.
2703 Completely rewritten by Tels http://bloodgate.com in late 2000, 2001.