1N/Apackage Math::BigFloat;
1N/A
1N/A#
1N/A# Mike grinned. 'Two down, infinity to go' - Mike Nostrus in 'Before and After'
1N/A#
1N/A
1N/A# The following hash values are internally used:
1N/A# _e : exponent (ref to $CALC object)
1N/A# _m : mantissa (ref to $CALC object)
1N/A# _es : sign of _e
1N/A# sign : +,-,+inf,-inf, or "NaN" if not a number
1N/A# _a : accuracy
1N/A# _p : precision
1N/A
1N/A$VERSION = '1.44';
1N/Arequire 5.005;
1N/A
1N/Arequire Exporter;
1N/A@ISA = qw(Exporter Math::BigInt);
1N/A
1N/Ause strict;
1N/A# $_trap_inf and $_trap_nan are internal and should never be accessed from the outside
1N/Ause vars qw/$AUTOLOAD $accuracy $precision $div_scale $round_mode $rnd_mode
1N/A $upgrade $downgrade $_trap_nan $_trap_inf/;
1N/Amy $class = "Math::BigFloat";
1N/A
1N/Ause overload
1N/A'<=>' => sub { $_[2] ?
1N/A ref($_[0])->bcmp($_[1],$_[0]) :
1N/A ref($_[0])->bcmp($_[0],$_[1])},
1N/A'int' => sub { $_[0]->as_number() }, # 'trunc' to bigint
1N/A;
1N/A
1N/A##############################################################################
1N/A# global constants, flags and assorted stuff
1N/A
1N/A# the following are public, but their usage is not recommended. Use the
1N/A# accessor methods instead.
1N/A
1N/A# class constants, use Class->constant_name() to access
1N/A$round_mode = 'even'; # one of 'even', 'odd', '+inf', '-inf', 'zero' or 'trunc'
1N/A$accuracy = undef;
1N/A$precision = undef;
1N/A$div_scale = 40;
1N/A
1N/A$upgrade = undef;
1N/A$downgrade = undef;
1N/A# the package we are using for our private parts, defaults to:
1N/A# Math::BigInt->config()->{lib}
1N/Amy $MBI = 'Math::BigInt::Calc';
1N/A
1N/A# are NaNs ok? (otherwise it dies when encountering an NaN) set w/ config()
1N/A$_trap_nan = 0;
1N/A# the same for infinity
1N/A$_trap_inf = 0;
1N/A
1N/A# constant for easier life
1N/Amy $nan = 'NaN';
1N/A
1N/Amy $IMPORT = 0; # was import() called yet? used to make require work
1N/A
1N/A# some digits of accuracy for blog(undef,10); which we use in blog() for speed
1N/Amy $LOG_10 =
1N/A '2.3025850929940456840179914546843642076011014886287729760333279009675726097';
1N/Amy $LOG_10_A = length($LOG_10)-1;
1N/A# ditto for log(2)
1N/Amy $LOG_2 =
1N/A '0.6931471805599453094172321214581765680755001343602552541206800094933936220';
1N/Amy $LOG_2_A = length($LOG_2)-1;
1N/Amy $HALF = '0.5'; # made into an object if necc.
1N/A
1N/A##############################################################################
1N/A# the old code had $rnd_mode, so we need to support it, too
1N/A
1N/Asub TIESCALAR { my ($class) = @_; bless \$round_mode, $class; }
1N/Asub FETCH { return $round_mode; }
1N/Asub STORE { $rnd_mode = $_[0]->round_mode($_[1]); }
1N/A
1N/ABEGIN
1N/A {
1N/A # when someone set's $rnd_mode, we catch this and check the value to see
1N/A # whether it is valid or not.
1N/A $rnd_mode = 'even'; tie $rnd_mode, 'Math::BigFloat';
1N/A }
1N/A
1N/A##############################################################################
1N/A
1N/A{
1N/A # valid method aliases for AUTOLOAD
1N/A my %methods = map { $_ => 1 }
1N/A qw / fadd fsub fmul fdiv fround ffround fsqrt fmod fstr fsstr fpow fnorm
1N/A fint facmp fcmp fzero fnan finf finc fdec flog ffac
1N/A fceil ffloor frsft flsft fone flog froot
1N/A /;
1N/A # valid method's that can be hand-ed up (for AUTOLOAD)
1N/A my %hand_ups = map { $_ => 1 }
1N/A qw / is_nan is_inf is_negative is_positive is_pos is_neg
1N/A accuracy precision div_scale round_mode fneg fabs fnot
1N/A objectify upgrade downgrade
1N/A bone binf bnan bzero
1N/A /;
1N/A
1N/A sub method_alias { exists $methods{$_[0]||''}; }
1N/A sub method_hand_up { exists $hand_ups{$_[0]||''}; }
1N/A}
1N/A
1N/A##############################################################################
1N/A# constructors
1N/A
1N/Asub new
1N/A {
1N/A # create a new BigFloat object from a string or another bigfloat object.
1N/A # _e: exponent
1N/A # _m: mantissa
1N/A # sign => sign (+/-), or "NaN"
1N/A
1N/A my ($class,$wanted,@r) = @_;
1N/A
1N/A # avoid numify-calls by not using || on $wanted!
1N/A return $class->bzero() if !defined $wanted; # default to 0
1N/A return $wanted->copy() if UNIVERSAL::isa($wanted,'Math::BigFloat');
1N/A
1N/A $class->import() if $IMPORT == 0; # make require work
1N/A
1N/A my $self = {}; bless $self, $class;
1N/A # shortcut for bigints and its subclasses
1N/A if ((ref($wanted)) && (ref($wanted) ne $class))
1N/A {
1N/A $self->{_m} = $wanted->as_number()->{value}; # get us a bigint copy
1N/A $self->{_e} = $MBI->_zero();
1N/A $self->{_es} = '+';
1N/A $self->{sign} = $wanted->sign();
1N/A return $self->bnorm();
1N/A }
1N/A # got string
1N/A # handle '+inf', '-inf' first
1N/A if ($wanted =~ /^[+-]?inf$/)
1N/A {
1N/A return $downgrade->new($wanted) if $downgrade;
1N/A
1N/A $self->{_e} = $MBI->_zero();
1N/A $self->{_es} = '+';
1N/A $self->{_m} = $MBI->_zero();
1N/A $self->{sign} = $wanted;
1N/A $self->{sign} = '+inf' if $self->{sign} eq 'inf';
1N/A return $self->bnorm();
1N/A }
1N/A
1N/A my ($mis,$miv,$mfv,$es,$ev) = Math::BigInt::_split($wanted);
1N/A if (!ref $mis)
1N/A {
1N/A if ($_trap_nan)
1N/A {
1N/A require Carp;
1N/A Carp::croak ("$wanted is not a number initialized to $class");
1N/A }
1N/A
1N/A return $downgrade->bnan() if $downgrade;
1N/A
1N/A $self->{_e} = $MBI->_zero();
1N/A $self->{_es} = '+';
1N/A $self->{_m} = $MBI->_zero();
1N/A $self->{sign} = $nan;
1N/A }
1N/A else
1N/A {
1N/A # make integer from mantissa by adjusting exp, then convert to int
1N/A $self->{_e} = $MBI->_new($$ev); # exponent
1N/A $self->{_es} = $$es || '+';
1N/A my $mantissa = "$$miv$$mfv"; # create mant.
1N/A $mantissa =~ s/^0+(\d)/$1/; # strip leading zeros
1N/A $self->{_m} = $MBI->_new($mantissa); # create mant.
1N/A
1N/A # 3.123E0 = 3123E-3, and 3.123E-2 => 3123E-5
1N/A if (CORE::length($$mfv) != 0)
1N/A {
1N/A my $len = $MBI->_new( CORE::length($$mfv));
1N/A ($self->{_e}, $self->{_es}) =
1N/A _e_sub ($self->{_e}, $len, $self->{_es}, '+');
1N/A }
1N/A $self->{sign} = $$mis;
1N/A
1N/A # we can only have trailing zeros on the mantissa of $$mfv eq ''
1N/A if (CORE::length($$mfv) == 0)
1N/A {
1N/A my $zeros = $MBI->_zeros($self->{_m}); # correct for trailing zeros
1N/A if ($zeros != 0)
1N/A {
1N/A my $z = $MBI->_new($zeros);
1N/A $MBI->_rsft ( $self->{_m}, $z, 10);
1N/A _e_add ( $self->{_e}, $z, $self->{_es}, '+');
1N/A }
1N/A }
1N/A # for something like 0Ey, set y to 1, and -0 => +0
1N/A $self->{sign} = '+', $self->{_e} = $MBI->_one()
1N/A if $MBI->_is_zero($self->{_m});
1N/A return $self->round(@r) if !$downgrade;
1N/A }
1N/A # if downgrade, inf, NaN or integers go down
1N/A
1N/A if ($downgrade && $self->{_es} eq '+')
1N/A {
1N/A if ($MBI->_is_zero( $self->{_e} ))
1N/A {
1N/A return $downgrade->new($$mis . $MBI->_str( $self->{_m} ));
1N/A }
1N/A return $downgrade->new($self->bsstr());
1N/A }
1N/A $self->bnorm()->round(@r); # first normalize, then round
1N/A }
1N/A
1N/Asub copy
1N/A {
1N/A my ($c,$x);
1N/A if (@_ > 1)
1N/A {
1N/A # if two arguments, the first one is the class to "swallow" subclasses
1N/A ($c,$x) = @_;
1N/A }
1N/A else
1N/A {
1N/A $x = shift;
1N/A $c = ref($x);
1N/A }
1N/A return unless ref($x); # only for objects
1N/A
1N/A my $self = {}; bless $self,$c;
1N/A
1N/A $self->{sign} = $x->{sign};
1N/A $self->{_es} = $x->{_es};
1N/A $self->{_m} = $MBI->_copy($x->{_m});
1N/A $self->{_e} = $MBI->_copy($x->{_e});
1N/A $self->{_a} = $x->{_a} if defined $x->{_a};
1N/A $self->{_p} = $x->{_p} if defined $x->{_p};
1N/A $self;
1N/A }
1N/A
1N/Asub _bnan
1N/A {
1N/A # used by parent class bone() to initialize number to NaN
1N/A my $self = shift;
1N/A
1N/A if ($_trap_nan)
1N/A {
1N/A require Carp;
1N/A my $class = ref($self);
1N/A Carp::croak ("Tried to set $self to NaN in $class\::_bnan()");
1N/A }
1N/A
1N/A $IMPORT=1; # call our import only once
1N/A $self->{_m} = $MBI->_zero();
1N/A $self->{_e} = $MBI->_zero();
1N/A $self->{_es} = '+';
1N/A }
1N/A
1N/Asub _binf
1N/A {
1N/A # used by parent class bone() to initialize number to +-inf
1N/A my $self = shift;
1N/A
1N/A if ($_trap_inf)
1N/A {
1N/A require Carp;
1N/A my $class = ref($self);
1N/A Carp::croak ("Tried to set $self to +-inf in $class\::_binf()");
1N/A }
1N/A
1N/A $IMPORT=1; # call our import only once
1N/A $self->{_m} = $MBI->_zero();
1N/A $self->{_e} = $MBI->_zero();
1N/A $self->{_es} = '+';
1N/A }
1N/A
1N/Asub _bone
1N/A {
1N/A # used by parent class bone() to initialize number to 1
1N/A my $self = shift;
1N/A $IMPORT=1; # call our import only once
1N/A $self->{_m} = $MBI->_one();
1N/A $self->{_e} = $MBI->_zero();
1N/A $self->{_es} = '+';
1N/A }
1N/A
1N/Asub _bzero
1N/A {
1N/A # used by parent class bone() to initialize number to 0
1N/A my $self = shift;
1N/A $IMPORT=1; # call our import only once
1N/A $self->{_m} = $MBI->_zero();
1N/A $self->{_e} = $MBI->_one();
1N/A $self->{_es} = '+';
1N/A }
1N/A
1N/Asub isa
1N/A {
1N/A my ($self,$class) = @_;
1N/A return if $class =~ /^Math::BigInt/; # we aren't one of these
1N/A UNIVERSAL::isa($self,$class);
1N/A }
1N/A
1N/Asub config
1N/A {
1N/A # return (later set?) configuration data as hash ref
1N/A my $class = shift || 'Math::BigFloat';
1N/A
1N/A my $cfg = $class->SUPER::config(@_);
1N/A
1N/A # now we need only to override the ones that are different from our parent
1N/A $cfg->{class} = $class;
1N/A $cfg->{with} = $MBI;
1N/A $cfg;
1N/A }
1N/A
1N/A##############################################################################
1N/A# string conversation
1N/A
1N/Asub bstr
1N/A {
1N/A # (ref to BFLOAT or num_str ) return num_str
1N/A # Convert number from internal format to (non-scientific) string format.
1N/A # internal format is always normalized (no leading zeros, "-0" => "+0")
1N/A my ($self,$x) = ref($_[0]) ? (ref($_[0]),$_[0]) : objectify(1,@_);
1N/A
1N/A if ($x->{sign} !~ /^[+-]$/)
1N/A {
1N/A return $x->{sign} unless $x->{sign} eq '+inf'; # -inf, NaN
1N/A return 'inf'; # +inf
1N/A }
1N/A
1N/A my $es = '0'; my $len = 1; my $cad = 0; my $dot = '.';
1N/A
1N/A # $x is zero?
1N/A my $not_zero = !($x->{sign} eq '+' && $MBI->_is_zero($x->{_m}));
1N/A if ($not_zero)
1N/A {
1N/A $es = $MBI->_str($x->{_m});
1N/A $len = CORE::length($es);
1N/A my $e = $MBI->_num($x->{_e});
1N/A $e = -$e if $x->{_es} eq '-';
1N/A if ($e < 0)
1N/A {
1N/A $dot = '';
1N/A # if _e is bigger than a scalar, the following will blow your memory
1N/A if ($e <= -$len)
1N/A {
1N/A my $r = abs($e) - $len;
1N/A $es = '0.'. ('0' x $r) . $es; $cad = -($len+$r);
1N/A }
1N/A else
1N/A {
1N/A substr($es,$e,0) = '.'; $cad = $MBI->_num($x->{_e});
1N/A $cad = -$cad if $x->{_es} eq '-';
1N/A }
1N/A }
1N/A elsif ($e > 0)
1N/A {
1N/A # expand with zeros
1N/A $es .= '0' x $e; $len += $e; $cad = 0;
1N/A }
1N/A } # if not zero
1N/A
1N/A $es = '-'.$es if $x->{sign} eq '-';
1N/A # if set accuracy or precision, pad with zeros on the right side
1N/A if ((defined $x->{_a}) && ($not_zero))
1N/A {
1N/A # 123400 => 6, 0.1234 => 4, 0.001234 => 4
1N/A my $zeros = $x->{_a} - $cad; # cad == 0 => 12340
1N/A $zeros = $x->{_a} - $len if $cad != $len;
1N/A $es .= $dot.'0' x $zeros if $zeros > 0;
1N/A }
1N/A elsif ((($x->{_p} || 0) < 0))
1N/A {
1N/A # 123400 => 6, 0.1234 => 4, 0.001234 => 6
1N/A my $zeros = -$x->{_p} + $cad;
1N/A $es .= $dot.'0' x $zeros if $zeros > 0;
1N/A }
1N/A $es;
1N/A }
1N/A
1N/Asub bsstr
1N/A {
1N/A # (ref to BFLOAT or num_str ) return num_str
1N/A # Convert number from internal format to scientific string format.
1N/A # internal format is always normalized (no leading zeros, "-0E0" => "+0E0")
1N/A my ($self,$x) = ref($_[0]) ? (ref($_[0]),$_[0]) : objectify(1,@_);
1N/A
1N/A if ($x->{sign} !~ /^[+-]$/)
1N/A {
1N/A return $x->{sign} unless $x->{sign} eq '+inf'; # -inf, NaN
1N/A return 'inf'; # +inf
1N/A }
1N/A my $sep = 'e'.$x->{_es};
1N/A my $sign = $x->{sign}; $sign = '' if $sign eq '+';
1N/A $sign . $MBI->_str($x->{_m}) . $sep . $MBI->_str($x->{_e});
1N/A }
1N/A
1N/Asub numify
1N/A {
1N/A # Make a number from a BigFloat object
1N/A # simple return a string and let Perl's atoi()/atof() handle the rest
1N/A my ($self,$x) = ref($_[0]) ? (undef,$_[0]) : objectify(1,@_);
1N/A $x->bsstr();
1N/A }
1N/A
1N/A##############################################################################
1N/A# public stuff (usually prefixed with "b")
1N/A
1N/A# tels 2001-08-04
1N/A# XXX TODO this must be overwritten and return NaN for non-integer values
1N/A# band(), bior(), bxor(), too
1N/A#sub bnot
1N/A# {
1N/A# $class->SUPER::bnot($class,@_);
1N/A# }
1N/A
1N/Asub bcmp
1N/A {
1N/A # Compares 2 values. Returns one of undef, <0, =0, >0. (suitable for sort)
1N/A
1N/A # set up parameters
1N/A my ($self,$x,$y) = (ref($_[0]),@_);
1N/A # objectify is costly, so avoid it
1N/A if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1])))
1N/A {
1N/A ($self,$x,$y) = objectify(2,@_);
1N/A }
1N/A
1N/A return $upgrade->bcmp($x,$y) if defined $upgrade &&
1N/A ((!$x->isa($self)) || (!$y->isa($self)));
1N/A
1N/A if (($x->{sign} !~ /^[+-]$/) || ($y->{sign} !~ /^[+-]$/))
1N/A {
1N/A # handle +-inf and NaN
1N/A return undef if (($x->{sign} eq $nan) || ($y->{sign} eq $nan));
1N/A return 0 if ($x->{sign} eq $y->{sign}) && ($x->{sign} =~ /^[+-]inf$/);
1N/A return +1 if $x->{sign} eq '+inf';
1N/A return -1 if $x->{sign} eq '-inf';
1N/A return -1 if $y->{sign} eq '+inf';
1N/A return +1;
1N/A }
1N/A
1N/A # check sign for speed first
1N/A return 1 if $x->{sign} eq '+' && $y->{sign} eq '-'; # does also 0 <=> -y
1N/A return -1 if $x->{sign} eq '-' && $y->{sign} eq '+'; # does also -x <=> 0
1N/A
1N/A # shortcut
1N/A my $xz = $x->is_zero();
1N/A my $yz = $y->is_zero();
1N/A return 0 if $xz && $yz; # 0 <=> 0
1N/A return -1 if $xz && $y->{sign} eq '+'; # 0 <=> +y
1N/A return 1 if $yz && $x->{sign} eq '+'; # +x <=> 0
1N/A
1N/A # adjust so that exponents are equal
1N/A my $lxm = $MBI->_len($x->{_m});
1N/A my $lym = $MBI->_len($y->{_m});
1N/A # the numify somewhat limits our length, but makes it much faster
1N/A my ($xes,$yes) = (1,1);
1N/A $xes = -1 if $x->{_es} ne '+';
1N/A $yes = -1 if $y->{_es} ne '+';
1N/A my $lx = $lxm + $xes * $MBI->_num($x->{_e});
1N/A my $ly = $lym + $yes * $MBI->_num($y->{_e});
1N/A my $l = $lx - $ly; $l = -$l if $x->{sign} eq '-';
1N/A return $l <=> 0 if $l != 0;
1N/A
1N/A # lengths (corrected by exponent) are equal
1N/A # so make mantissa equal length by padding with zero (shift left)
1N/A my $diff = $lxm - $lym;
1N/A my $xm = $x->{_m}; # not yet copy it
1N/A my $ym = $y->{_m};
1N/A if ($diff > 0)
1N/A {
1N/A $ym = $MBI->_copy($y->{_m});
1N/A $ym = $MBI->_lsft($ym, $MBI->_new($diff), 10);
1N/A }
1N/A elsif ($diff < 0)
1N/A {
1N/A $xm = $MBI->_copy($x->{_m});
1N/A $xm = $MBI->_lsft($xm, $MBI->_new(-$diff), 10);
1N/A }
1N/A my $rc = $MBI->_acmp($xm,$ym);
1N/A $rc = -$rc if $x->{sign} eq '-'; # -124 < -123
1N/A $rc <=> 0;
1N/A }
1N/A
1N/Asub bacmp
1N/A {
1N/A # Compares 2 values, ignoring their signs.
1N/A # Returns one of undef, <0, =0, >0. (suitable for sort)
1N/A
1N/A # set up parameters
1N/A my ($self,$x,$y) = (ref($_[0]),@_);
1N/A # objectify is costly, so avoid it
1N/A if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1])))
1N/A {
1N/A ($self,$x,$y) = objectify(2,@_);
1N/A }
1N/A
1N/A return $upgrade->bacmp($x,$y) if defined $upgrade &&
1N/A ((!$x->isa($self)) || (!$y->isa($self)));
1N/A
1N/A # handle +-inf and NaN's
1N/A if ($x->{sign} !~ /^[+-]$/ || $y->{sign} !~ /^[+-]$/)
1N/A {
1N/A return undef if (($x->{sign} eq $nan) || ($y->{sign} eq $nan));
1N/A return 0 if ($x->is_inf() && $y->is_inf());
1N/A return 1 if ($x->is_inf() && !$y->is_inf());
1N/A return -1;
1N/A }
1N/A
1N/A # shortcut
1N/A my $xz = $x->is_zero();
1N/A my $yz = $y->is_zero();
1N/A return 0 if $xz && $yz; # 0 <=> 0
1N/A return -1 if $xz && !$yz; # 0 <=> +y
1N/A return 1 if $yz && !$xz; # +x <=> 0
1N/A
1N/A # adjust so that exponents are equal
1N/A my $lxm = $MBI->_len($x->{_m});
1N/A my $lym = $MBI->_len($y->{_m});
1N/A my ($xes,$yes) = (1,1);
1N/A $xes = -1 if $x->{_es} ne '+';
1N/A $yes = -1 if $y->{_es} ne '+';
1N/A # the numify somewhat limits our length, but makes it much faster
1N/A my $lx = $lxm + $xes * $MBI->_num($x->{_e});
1N/A my $ly = $lym + $yes * $MBI->_num($y->{_e});
1N/A my $l = $lx - $ly;
1N/A return $l <=> 0 if $l != 0;
1N/A
1N/A # lengths (corrected by exponent) are equal
1N/A # so make mantissa equal-length by padding with zero (shift left)
1N/A my $diff = $lxm - $lym;
1N/A my $xm = $x->{_m}; # not yet copy it
1N/A my $ym = $y->{_m};
1N/A if ($diff > 0)
1N/A {
1N/A $ym = $MBI->_copy($y->{_m});
1N/A $ym = $MBI->_lsft($ym, $MBI->_new($diff), 10);
1N/A }
1N/A elsif ($diff < 0)
1N/A {
1N/A $xm = $MBI->_copy($x->{_m});
1N/A $xm = $MBI->_lsft($xm, $MBI->_new(-$diff), 10);
1N/A }
1N/A $MBI->_acmp($xm,$ym);
1N/A }
1N/A
1N/Asub badd
1N/A {
1N/A # add second arg (BFLOAT or string) to first (BFLOAT) (modifies first)
1N/A # return result as BFLOAT
1N/A
1N/A # set up parameters
1N/A my ($self,$x,$y,$a,$p,$r) = (ref($_[0]),@_);
1N/A # objectify is costly, so avoid it
1N/A if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1])))
1N/A {
1N/A ($self,$x,$y,$a,$p,$r) = objectify(2,@_);
1N/A }
1N/A
1N/A # inf and NaN handling
1N/A if (($x->{sign} !~ /^[+-]$/) || ($y->{sign} !~ /^[+-]$/))
1N/A {
1N/A # NaN first
1N/A return $x->bnan() if (($x->{sign} eq $nan) || ($y->{sign} eq $nan));
1N/A # inf handling
1N/A if (($x->{sign} =~ /^[+-]inf$/) && ($y->{sign} =~ /^[+-]inf$/))
1N/A {
1N/A # +inf++inf or -inf+-inf => same, rest is NaN
1N/A return $x if $x->{sign} eq $y->{sign};
1N/A return $x->bnan();
1N/A }
1N/A # +-inf + something => +inf; something +-inf => +-inf
1N/A $x->{sign} = $y->{sign}, return $x if $y->{sign} =~ /^[+-]inf$/;
1N/A return $x;
1N/A }
1N/A
1N/A return $upgrade->badd($x,$y,$a,$p,$r) if defined $upgrade &&
1N/A ((!$x->isa($self)) || (!$y->isa($self)));
1N/A
1N/A # speed: no add for 0+y or x+0
1N/A return $x->bround($a,$p,$r) if $y->is_zero(); # x+0
1N/A if ($x->is_zero()) # 0+y
1N/A {
1N/A # make copy, clobbering up x (modify in place!)
1N/A $x->{_e} = $MBI->_copy($y->{_e});
1N/A $x->{_es} = $y->{_es};
1N/A $x->{_m} = $MBI->_copy($y->{_m});
1N/A $x->{sign} = $y->{sign} || $nan;
1N/A return $x->round($a,$p,$r,$y);
1N/A }
1N/A
1N/A # take lower of the two e's and adapt m1 to it to match m2
1N/A my $e = $y->{_e};
1N/A $e = $MBI->_zero() if !defined $e; # if no BFLOAT?
1N/A $e = $MBI->_copy($e); # make copy (didn't do it yet)
1N/A
1N/A my $es;
1N/A
1N/A ($e,$es) = _e_sub($e, $x->{_e}, $y->{_es} || '+', $x->{_es});
1N/A
1N/A my $add = $MBI->_copy($y->{_m});
1N/A
1N/A if ($es eq '-') # < 0
1N/A {
1N/A $MBI->_lsft( $x->{_m}, $e, 10);
1N/A ($x->{_e},$x->{_es}) = _e_add($x->{_e}, $e, $x->{_es}, $es);
1N/A }
1N/A elsif (!$MBI->_is_zero($e)) # > 0
1N/A {
1N/A $MBI->_lsft($add, $e, 10);
1N/A }
1N/A # else: both e are the same, so just leave them
1N/A
1N/A if ($x->{sign} eq $y->{sign})
1N/A {
1N/A # add
1N/A $x->{_m} = $MBI->_add($x->{_m}, $add);
1N/A }
1N/A else
1N/A {
1N/A ($x->{_m}, $x->{sign}) =
1N/A _e_add($x->{_m}, $add, $x->{sign}, $y->{sign});
1N/A }
1N/A
1N/A # delete trailing zeros, then round
1N/A $x->bnorm()->round($a,$p,$r,$y);
1N/A }
1N/A
1N/Asub bsub
1N/A {
1N/A # (BigFloat or num_str, BigFloat or num_str) return BigFloat
1N/A # subtract second arg from first, modify first
1N/A
1N/A # set up parameters
1N/A my ($self,$x,$y,$a,$p,$r) = (ref($_[0]),@_);
1N/A # objectify is costly, so avoid it
1N/A if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1])))
1N/A {
1N/A ($self,$x,$y,$a,$p,$r) = objectify(2,@_);
1N/A }
1N/A
1N/A if ($y->is_zero()) # still round for not adding zero
1N/A {
1N/A return $x->round($a,$p,$r);
1N/A }
1N/A
1N/A # $x - $y = -$x + $y
1N/A $y->{sign} =~ tr/+-/-+/; # does nothing for NaN
1N/A $x->badd($y,$a,$p,$r); # badd does not leave internal zeros
1N/A $y->{sign} =~ tr/+-/-+/; # refix $y (does nothing for NaN)
1N/A $x; # already rounded by badd()
1N/A }
1N/A
1N/Asub binc
1N/A {
1N/A # increment arg by one
1N/A my ($self,$x,@r) = ref($_[0]) ? (ref($_[0]),@_) : objectify(1,@_);
1N/A
1N/A if ($x->{_es} eq '-')
1N/A {
1N/A return $x->badd($self->bone(),@r); # digits after dot
1N/A }
1N/A
1N/A if (!$MBI->_is_zero($x->{_e})) # _e == 0 for NaN, inf, -inf
1N/A {
1N/A # 1e2 => 100, so after the shift below _m has a '0' as last digit
1N/A $x->{_m} = $MBI->_lsft($x->{_m}, $x->{_e},10); # 1e2 => 100
1N/A $x->{_e} = $MBI->_zero(); # normalize
1N/A $x->{_es} = '+';
1N/A # we know that the last digit of $x will be '1' or '9', depending on the
1N/A # sign
1N/A }
1N/A # now $x->{_e} == 0
1N/A if ($x->{sign} eq '+')
1N/A {
1N/A $MBI->_inc($x->{_m});
1N/A return $x->bnorm()->bround(@r);
1N/A }
1N/A elsif ($x->{sign} eq '-')
1N/A {
1N/A $MBI->_dec($x->{_m});
1N/A $x->{sign} = '+' if $MBI->_is_zero($x->{_m}); # -1 +1 => -0 => +0
1N/A return $x->bnorm()->bround(@r);
1N/A }
1N/A # inf, nan handling etc
1N/A $x->badd($self->bone(),@r); # badd() does round
1N/A }
1N/A
1N/Asub bdec
1N/A {
1N/A # decrement arg by one
1N/A my ($self,$x,@r) = ref($_[0]) ? (ref($_[0]),@_) : objectify(1,@_);
1N/A
1N/A if ($x->{_es} eq '-')
1N/A {
1N/A return $x->badd($self->bone('-'),@r); # digits after dot
1N/A }
1N/A
1N/A if (!$MBI->_is_zero($x->{_e}))
1N/A {
1N/A $x->{_m} = $MBI->_lsft($x->{_m}, $x->{_e},10); # 1e2 => 100
1N/A $x->{_e} = $MBI->_zero(); # normalize
1N/A $x->{_es} = '+';
1N/A }
1N/A # now $x->{_e} == 0
1N/A my $zero = $x->is_zero();
1N/A # <= 0
1N/A if (($x->{sign} eq '-') || $zero)
1N/A {
1N/A $MBI->_inc($x->{_m});
1N/A $x->{sign} = '-' if $zero; # 0 => 1 => -1
1N/A $x->{sign} = '+' if $MBI->_is_zero($x->{_m}); # -1 +1 => -0 => +0
1N/A return $x->bnorm()->round(@r);
1N/A }
1N/A # > 0
1N/A elsif ($x->{sign} eq '+')
1N/A {
1N/A $MBI->_dec($x->{_m});
1N/A return $x->bnorm()->round(@r);
1N/A }
1N/A # inf, nan handling etc
1N/A $x->badd($self->bone('-'),@r); # does round
1N/A }
1N/A
1N/Asub DEBUG () { 0; }
1N/A
1N/Asub blog
1N/A {
1N/A my ($self,$x,$base,$a,$p,$r) = ref($_[0]) ? (ref($_[0]),@_) : objectify(1,@_);
1N/A
1N/A # $base > 0, $base != 1; if $base == undef default to $base == e
1N/A # $x >= 0
1N/A
1N/A # we need to limit the accuracy to protect against overflow
1N/A my $fallback = 0;
1N/A my ($scale,@params);
1N/A ($x,@params) = $x->_find_round_parameters($a,$p,$r);
1N/A
1N/A # also takes care of the "error in _find_round_parameters?" case
1N/A return $x->bnan() if $x->{sign} ne '+' || $x->is_zero();
1N/A
1N/A
1N/A # no rounding at all, so must use fallback
1N/A if (scalar @params == 0)
1N/A {
1N/A # simulate old behaviour
1N/A $params[0] = $self->div_scale(); # and round to it as accuracy
1N/A $params[1] = undef; # P = undef
1N/A $scale = $params[0]+4; # at least four more for proper round
1N/A $params[2] = $r; # round mode by caller or undef
1N/A $fallback = 1; # to clear a/p afterwards
1N/A }
1N/A else
1N/A {
1N/A # the 4 below is empirical, and there might be cases where it is not
1N/A # enough...
1N/A $scale = abs($params[0] || $params[1]) + 4; # take whatever is defined
1N/A }
1N/A
1N/A return $x->bzero(@params) if $x->is_one();
1N/A # base not defined => base == Euler's constant e
1N/A if (defined $base)
1N/A {
1N/A # make object, since we don't feed it through objectify() to still get the
1N/A # case of $base == undef
1N/A $base = $self->new($base) unless ref($base);
1N/A # $base > 0; $base != 1
1N/A return $x->bnan() if $base->is_zero() || $base->is_one() ||
1N/A $base->{sign} ne '+';
1N/A # if $x == $base, we know the result must be 1.0
1N/A return $x->bone('+',@params) if $x->bcmp($base) == 0;
1N/A }
1N/A
1N/A # when user set globals, they would interfere with our calculation, so
1N/A # disable them and later re-enable them
1N/A no strict 'refs';
1N/A my $abr = "$self\::accuracy"; my $ab = $$abr; $$abr = undef;
1N/A my $pbr = "$self\::precision"; my $pb = $$pbr; $$pbr = undef;
1N/A # we also need to disable any set A or P on $x (_find_round_parameters took
1N/A # them already into account), since these would interfere, too
1N/A delete $x->{_a}; delete $x->{_p};
1N/A # need to disable $upgrade in BigInt, to avoid deep recursion
1N/A local $Math::BigInt::upgrade = undef;
1N/A local $Math::BigFloat::downgrade = undef;
1N/A
1N/A # upgrade $x if $x is not a BigFloat (handle BigInt input)
1N/A if (!$x->isa('Math::BigFloat'))
1N/A {
1N/A $x = Math::BigFloat->new($x);
1N/A $self = ref($x);
1N/A }
1N/A
1N/A my $done = 0;
1N/A
1N/A # If the base is defined and an integer, try to calculate integer result
1N/A # first. This is very fast, and in case the real result was found, we can
1N/A # stop right here.
1N/A if (defined $base && $base->is_int() && $x->is_int())
1N/A {
1N/A my $i = $MBI->_copy( $x->{_m} );
1N/A $MBI->_lsft( $i, $x->{_e}, 10 ) unless $MBI->_is_zero($x->{_e});
1N/A my $int = Math::BigInt->bzero();
1N/A $int->{value} = $i;
1N/A $int->blog($base->as_number());
1N/A # if ($exact)
1N/A if ($base->as_number()->bpow($int) == $x)
1N/A {
1N/A # found result, return it
1N/A $x->{_m} = $int->{value};
1N/A $x->{_e} = $MBI->_zero();
1N/A $x->{_es} = '+';
1N/A $x->bnorm();
1N/A $done = 1;
1N/A }
1N/A }
1N/A
1N/A if ($done == 0)
1N/A {
1N/A # first calculate the log to base e (using reduction by 10 (and probably 2))
1N/A $self->_log_10($x,$scale);
1N/A
1N/A # and if a different base was requested, convert it
1N/A if (defined $base)
1N/A {
1N/A $base = Math::BigFloat->new($base) unless $base->isa('Math::BigFloat');
1N/A # not ln, but some other base (don't modify $base)
1N/A $x->bdiv( $base->copy()->blog(undef,$scale), $scale );
1N/A }
1N/A }
1N/A
1N/A # shortcut to not run through _find_round_parameters again
1N/A if (defined $params[0])
1N/A {
1N/A $x->bround($params[0],$params[2]); # then round accordingly
1N/A }
1N/A else
1N/A {
1N/A $x->bfround($params[1],$params[2]); # then round accordingly
1N/A }
1N/A if ($fallback)
1N/A {
1N/A # clear a/p after round, since user did not request it
1N/A delete $x->{_a}; delete $x->{_p};
1N/A }
1N/A # restore globals
1N/A $$abr = $ab; $$pbr = $pb;
1N/A
1N/A $x;
1N/A }
1N/A
1N/Asub _log
1N/A {
1N/A # internal log function to calculate ln() based on Taylor series.
1N/A # Modifies $x in place.
1N/A my ($self,$x,$scale) = @_;
1N/A
1N/A # in case of $x == 1, result is 0
1N/A return $x->bzero() if $x->is_one();
1N/A
1N/A # http://www.efunda.com/math/taylor_series/logarithmic.cfm?search_string=log
1N/A
1N/A # u = x-1, v = x+1
1N/A # _ _
1N/A # Taylor: | u 1 u^3 1 u^5 |
1N/A # ln (x) = 2 | --- + - * --- + - * --- + ... | x > 0
1N/A # |_ v 3 v^3 5 v^5 _|
1N/A
1N/A # This takes much more steps to calculate the result and is thus not used
1N/A # u = x-1
1N/A # _ _
1N/A # Taylor: | u 1 u^2 1 u^3 |
1N/A # ln (x) = 2 | --- + - * --- + - * --- + ... | x > 1/2
1N/A # |_ x 2 x^2 3 x^3 _|
1N/A
1N/A my ($limit,$v,$u,$below,$factor,$two,$next,$over,$f);
1N/A
1N/A $v = $x->copy(); $v->binc(); # v = x+1
1N/A $x->bdec(); $u = $x->copy(); # u = x-1; x = x-1
1N/A $x->bdiv($v,$scale); # first term: u/v
1N/A $below = $v->copy();
1N/A $over = $u->copy();
1N/A $u *= $u; $v *= $v; # u^2, v^2
1N/A $below->bmul($v); # u^3, v^3
1N/A $over->bmul($u);
1N/A $factor = $self->new(3); $f = $self->new(2);
1N/A
1N/A my $steps = 0 if DEBUG;
1N/A $limit = $self->new("1E-". ($scale-1));
1N/A while (3 < 5)
1N/A {
1N/A # we calculate the next term, and add it to the last
1N/A # when the next term is below our limit, it won't affect the outcome
1N/A # anymore, so we stop
1N/A
1N/A # calculating the next term simple from over/below will result in quite
1N/A # a time hog if the input has many digits, since over and below will
1N/A # accumulate more and more digits, and the result will also have many
1N/A # digits, but in the end it is rounded to $scale digits anyway. So if we
1N/A # round $over and $below first, we save a lot of time for the division
1N/A # (not with log(1.2345), but try log (123**123) to see what I mean. This
1N/A # can introduce a rounding error if the division result would be f.i.
1N/A # 0.1234500000001 and we round it to 5 digits it would become 0.12346, but
1N/A # if we truncated $over and $below we might get 0.12345. Does this matter
1N/A # for the end result? So we give $over and $below 4 more digits to be
1N/A # on the safe side (unscientific error handling as usual... :+D
1N/A
1N/A $next = $over->copy->bround($scale+4)->bdiv(
1N/A $below->copy->bmul($factor)->bround($scale+4),
1N/A $scale);
1N/A
1N/A## old version:
1N/A## $next = $over->copy()->bdiv($below->copy()->bmul($factor),$scale);
1N/A
1N/A last if $next->bacmp($limit) <= 0;
1N/A
1N/A delete $next->{_a}; delete $next->{_p};
1N/A $x->badd($next);
1N/A # calculate things for the next term
1N/A $over *= $u; $below *= $v; $factor->badd($f);
1N/A if (DEBUG)
1N/A {
1N/A $steps++; print "step $steps = $x\n" if $steps % 10 == 0;
1N/A }
1N/A }
1N/A $x->bmul($f); # $x *= 2
1N/A print "took $steps steps\n" if DEBUG;
1N/A }
1N/A
1N/Asub _log_10
1N/A {
1N/A # Internal log function based on reducing input to the range of 0.1 .. 9.99
1N/A # and then "correcting" the result to the proper one. Modifies $x in place.
1N/A my ($self,$x,$scale) = @_;
1N/A
1N/A # taking blog() from numbers greater than 10 takes a *very long* time, so we
1N/A # break the computation down into parts based on the observation that:
1N/A # blog(x*y) = blog(x) + blog(y)
1N/A # We set $y here to multiples of 10 so that $x is below 1 (the smaller $x is
1N/A # the faster it get's, especially because 2*$x takes about 10 times as long,
1N/A # so by dividing $x by 10 we make it at least factor 100 faster...)
1N/A
1N/A # The same observation is valid for numbers smaller than 0.1 (e.g. computing
1N/A # log(1) is fastest, and the farther away we get from 1, the longer it takes)
1N/A # so we also 'break' this down by multiplying $x with 10 and subtract the
1N/A # log(10) afterwards to get the correct result.
1N/A
1N/A # calculate nr of digits before dot
1N/A my $dbd = $MBI->_num($x->{_e});
1N/A $dbd = -$dbd if $x->{_es} eq '-';
1N/A $dbd += $MBI->_len($x->{_m});
1N/A
1N/A # more than one digit (e.g. at least 10), but *not* exactly 10 to avoid
1N/A # infinite recursion
1N/A
1N/A my $calc = 1; # do some calculation?
1N/A
1N/A # disable the shortcut for 10, since we need log(10) and this would recurse
1N/A # infinitely deep
1N/A if ($x->{_es} eq '+' && $MBI->_is_one($x->{_e}) && $MBI->_is_one($x->{_m}))
1N/A {
1N/A $dbd = 0; # disable shortcut
1N/A # we can use the cached value in these cases
1N/A if ($scale <= $LOG_10_A)
1N/A {
1N/A $x->bzero(); $x->badd($LOG_10);
1N/A $calc = 0; # no need to calc, but round
1N/A }
1N/A }
1N/A else
1N/A {
1N/A # disable the shortcut for 2, since we maybe have it cached
1N/A if (($MBI->_is_zero($x->{_e}) && $MBI->_is_two($x->{_m})))
1N/A {
1N/A $dbd = 0; # disable shortcut
1N/A # we can use the cached value in these cases
1N/A if ($scale <= $LOG_2_A)
1N/A {
1N/A $x->bzero(); $x->badd($LOG_2);
1N/A $calc = 0; # no need to calc, but round
1N/A }
1N/A }
1N/A }
1N/A
1N/A # if $x = 0.1, we know the result must be 0-log(10)
1N/A if ($calc != 0 && $x->{_es} eq '-' && $MBI->_is_one($x->{_e}) &&
1N/A $MBI->_is_one($x->{_m}))
1N/A {
1N/A $dbd = 0; # disable shortcut
1N/A # we can use the cached value in these cases
1N/A if ($scale <= $LOG_10_A)
1N/A {
1N/A $x->bzero(); $x->bsub($LOG_10);
1N/A $calc = 0; # no need to calc, but round
1N/A }
1N/A }
1N/A
1N/A return if $calc == 0; # already have the result
1N/A
1N/A # default: these correction factors are undef and thus not used
1N/A my $l_10; # value of ln(10) to A of $scale
1N/A my $l_2; # value of ln(2) to A of $scale
1N/A
1N/A # $x == 2 => 1, $x == 13 => 2, $x == 0.1 => 0, $x == 0.01 => -1
1N/A # so don't do this shortcut for 1 or 0
1N/A if (($dbd > 1) || ($dbd < 0))
1N/A {
1N/A # convert our cached value to an object if not already (avoid doing this
1N/A # at import() time, since not everybody needs this)
1N/A $LOG_10 = $self->new($LOG_10,undef,undef) unless ref $LOG_10;
1N/A
1N/A #print "x = $x, dbd = $dbd, calc = $calc\n";
1N/A # got more than one digit before the dot, or more than one zero after the
1N/A # dot, so do:
1N/A # log(123) == log(1.23) + log(10) * 2
1N/A # log(0.0123) == log(1.23) - log(10) * 2
1N/A
1N/A if ($scale <= $LOG_10_A)
1N/A {
1N/A # use cached value
1N/A $l_10 = $LOG_10->copy(); # copy for mul
1N/A }
1N/A else
1N/A {
1N/A # else: slower, compute it (but don't cache it, because it could be big)
1N/A # also disable downgrade for this code path
1N/A local $Math::BigFloat::downgrade = undef;
1N/A $l_10 = $self->new(10)->blog(undef,$scale); # scale+4, actually
1N/A }
1N/A $dbd-- if ($dbd > 1); # 20 => dbd=2, so make it dbd=1
1N/A $l_10->bmul( $self->new($dbd)); # log(10) * (digits_before_dot-1)
1N/A my $dbd_sign = '+';
1N/A if ($dbd < 0)
1N/A {
1N/A $dbd = -$dbd;
1N/A $dbd_sign = '-';
1N/A }
1N/A ($x->{_e}, $x->{_es}) =
1N/A _e_sub( $x->{_e}, $MBI->_new($dbd), $x->{_es}, $dbd_sign); # 123 => 1.23
1N/A
1N/A }
1N/A
1N/A # Now: 0.1 <= $x < 10 (and possible correction in l_10)
1N/A
1N/A ### Since $x in the range 0.5 .. 1.5 is MUCH faster, we do a repeated div
1N/A ### or mul by 2 (maximum times 3, since x < 10 and x > 0.1)
1N/A
1N/A $HALF = $self->new($HALF) unless ref($HALF);
1N/A
1N/A my $twos = 0; # default: none (0 times)
1N/A my $two = $self->new(2);
1N/A while ($x->bacmp($HALF) <= 0)
1N/A {
1N/A $twos--; $x->bmul($two);
1N/A }
1N/A while ($x->bacmp($two) >= 0)
1N/A {
1N/A $twos++; $x->bdiv($two,$scale+4); # keep all digits
1N/A }
1N/A # $twos > 0 => did mul 2, < 0 => did div 2 (never both)
1N/A # calculate correction factor based on ln(2)
1N/A if ($twos != 0)
1N/A {
1N/A $LOG_2 = $self->new($LOG_2,undef,undef) unless ref $LOG_2;
1N/A if ($scale <= $LOG_2_A)
1N/A {
1N/A # use cached value
1N/A $l_2 = $LOG_2->copy(); # copy for mul
1N/A }
1N/A else
1N/A {
1N/A # else: slower, compute it (but don't cache it, because it could be big)
1N/A # also disable downgrade for this code path
1N/A local $Math::BigFloat::downgrade = undef;
1N/A $l_2 = $two->blog(undef,$scale); # scale+4, actually
1N/A }
1N/A $l_2->bmul($twos); # * -2 => subtract, * 2 => add
1N/A }
1N/A
1N/A $self->_log($x,$scale); # need to do the "normal" way
1N/A $x->badd($l_10) if defined $l_10; # correct it by ln(10)
1N/A $x->badd($l_2) if defined $l_2; # and maybe by ln(2)
1N/A # all done, $x contains now the result
1N/A }
1N/A
1N/Asub blcm
1N/A {
1N/A # (BFLOAT or num_str, BFLOAT or num_str) return BFLOAT
1N/A # does not modify arguments, but returns new object
1N/A # Lowest Common Multiplicator
1N/A
1N/A my ($self,@arg) = objectify(0,@_);
1N/A my $x = $self->new(shift @arg);
1N/A while (@arg) { $x = _lcm($x,shift @arg); }
1N/A $x;
1N/A }
1N/A
1N/Asub bgcd
1N/A {
1N/A # (BFLOAT or num_str, BFLOAT or num_str) return BINT
1N/A # does not modify arguments, but returns new object
1N/A # GCD -- Euclids algorithm Knuth Vol 2 pg 296
1N/A
1N/A my ($self,@arg) = objectify(0,@_);
1N/A my $x = $self->new(shift @arg);
1N/A while (@arg) { $x = _gcd($x,shift @arg); }
1N/A $x;
1N/A }
1N/A
1N/A##############################################################################
1N/A
1N/Asub _e_add
1N/A {
1N/A # Internal helper sub to take two positive integers and their signs and
1N/A # then add them. Input ($CALC,$CALC,('+'|'-'),('+'|'-')),
1N/A # output ($CALC,('+'|'-'))
1N/A my ($x,$y,$xs,$ys) = @_;
1N/A
1N/A # if the signs are equal we can add them (-5 + -3 => -(5 + 3) => -8)
1N/A if ($xs eq $ys)
1N/A {
1N/A $x = $MBI->_add ($x, $y ); # a+b
1N/A # the sign follows $xs
1N/A return ($x, $xs);
1N/A }
1N/A
1N/A my $a = $MBI->_acmp($x,$y);
1N/A if ($a > 0)
1N/A {
1N/A $x = $MBI->_sub ($x , $y); # abs sub
1N/A }
1N/A elsif ($a == 0)
1N/A {
1N/A $x = $MBI->_zero(); # result is 0
1N/A $xs = '+';
1N/A }
1N/A else # a < 0
1N/A {
1N/A $x = $MBI->_sub ( $y, $x, 1 ); # abs sub
1N/A $xs = $ys;
1N/A }
1N/A ($x,$xs);
1N/A }
1N/A
1N/Asub _e_sub
1N/A {
1N/A # Internal helper sub to take two positive integers and their signs and
1N/A # then subtract them. Input ($CALC,$CALC,('+'|'-'),('+'|'-')),
1N/A # output ($CALC,('+'|'-'))
1N/A my ($x,$y,$xs,$ys) = @_;
1N/A
1N/A # flip sign
1N/A $ys =~ tr/+-/-+/;
1N/A _e_add($x,$y,$xs,$ys); # call add (does subtract now)
1N/A }
1N/A
1N/A###############################################################################
1N/A# is_foo methods (is_negative, is_positive are inherited from BigInt)
1N/A
1N/Asub is_int
1N/A {
1N/A # return true if arg (BFLOAT or num_str) is an integer
1N/A my ($self,$x) = ref($_[0]) ? (undef,$_[0]) : objectify(1,@_);
1N/A
1N/A return 1 if ($x->{sign} =~ /^[+-]$/) && # NaN and +-inf aren't
1N/A $x->{_es} eq '+'; # 1e-1 => no integer
1N/A 0;
1N/A }
1N/A
1N/Asub is_zero
1N/A {
1N/A # return true if arg (BFLOAT or num_str) is zero
1N/A my ($self,$x) = ref($_[0]) ? (undef,$_[0]) : objectify(1,@_);
1N/A
1N/A return 1 if $x->{sign} eq '+' && $MBI->_is_zero($x->{_m});
1N/A 0;
1N/A }
1N/A
1N/Asub is_one
1N/A {
1N/A # return true if arg (BFLOAT or num_str) is +1 or -1 if signis given
1N/A my ($self,$x,$sign) = ref($_[0]) ? (undef,@_) : objectify(1,@_);
1N/A
1N/A $sign = '+' if !defined $sign || $sign ne '-';
1N/A return 1
1N/A if ($x->{sign} eq $sign &&
1N/A $MBI->_is_zero($x->{_e}) && $MBI->_is_one($x->{_m}));
1N/A 0;
1N/A }
1N/A
1N/Asub is_odd
1N/A {
1N/A # return true if arg (BFLOAT or num_str) is odd or false if even
1N/A my ($self,$x) = ref($_[0]) ? (undef,$_[0]) : objectify(1,@_);
1N/A
1N/A return 1 if ($x->{sign} =~ /^[+-]$/) && # NaN & +-inf aren't
1N/A ($MBI->_is_zero($x->{_e}) && $MBI->_is_odd($x->{_m}));
1N/A 0;
1N/A }
1N/A
1N/Asub is_even
1N/A {
1N/A # return true if arg (BINT or num_str) is even or false if odd
1N/A my ($self,$x) = ref($_[0]) ? (undef,$_[0]) : objectify(1,@_);
1N/A
1N/A return 0 if $x->{sign} !~ /^[+-]$/; # NaN & +-inf aren't
1N/A return 1 if ($x->{_es} eq '+' # 123.45 is never
1N/A && $MBI->_is_even($x->{_m})); # but 1200 is
1N/A 0;
1N/A }
1N/A
1N/Asub bmul
1N/A {
1N/A # multiply two numbers -- stolen from Knuth Vol 2 pg 233
1N/A # (BINT or num_str, BINT or num_str) return BINT
1N/A
1N/A # set up parameters
1N/A my ($self,$x,$y,$a,$p,$r) = (ref($_[0]),@_);
1N/A # objectify is costly, so avoid it
1N/A if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1])))
1N/A {
1N/A ($self,$x,$y,$a,$p,$r) = objectify(2,@_);
1N/A }
1N/A
1N/A return $x->bnan() if (($x->{sign} eq $nan) || ($y->{sign} eq $nan));
1N/A
1N/A # inf handling
1N/A if (($x->{sign} =~ /^[+-]inf$/) || ($y->{sign} =~ /^[+-]inf$/))
1N/A {
1N/A return $x->bnan() if $x->is_zero() || $y->is_zero();
1N/A # result will always be +-inf:
1N/A # +inf * +/+inf => +inf, -inf * -/-inf => +inf
1N/A # +inf * -/-inf => -inf, -inf * +/+inf => -inf
1N/A return $x->binf() if ($x->{sign} =~ /^\+/ && $y->{sign} =~ /^\+/);
1N/A return $x->binf() if ($x->{sign} =~ /^-/ && $y->{sign} =~ /^-/);
1N/A return $x->binf('-');
1N/A }
1N/A # handle result = 0
1N/A return $x->bzero() if $x->is_zero() || $y->is_zero();
1N/A
1N/A return $upgrade->bmul($x,$y,$a,$p,$r) if defined $upgrade &&
1N/A ((!$x->isa($self)) || (!$y->isa($self)));
1N/A
1N/A # aEb * cEd = (a*c)E(b+d)
1N/A $MBI->_mul($x->{_m},$y->{_m});
1N/A ($x->{_e}, $x->{_es}) = _e_add($x->{_e}, $y->{_e}, $x->{_es}, $y->{_es});
1N/A
1N/A # adjust sign:
1N/A $x->{sign} = $x->{sign} ne $y->{sign} ? '-' : '+';
1N/A return $x->bnorm()->round($a,$p,$r,$y);
1N/A }
1N/A
1N/Asub bdiv
1N/A {
1N/A # (dividend: BFLOAT or num_str, divisor: BFLOAT or num_str) return
1N/A # (BFLOAT,BFLOAT) (quo,rem) or BFLOAT (only rem)
1N/A
1N/A # set up parameters
1N/A my ($self,$x,$y,$a,$p,$r) = (ref($_[0]),@_);
1N/A # objectify is costly, so avoid it
1N/A if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1])))
1N/A {
1N/A ($self,$x,$y,$a,$p,$r) = objectify(2,@_);
1N/A }
1N/A
1N/A return $self->_div_inf($x,$y)
1N/A if (($x->{sign} !~ /^[+-]$/) || ($y->{sign} !~ /^[+-]$/) || $y->is_zero());
1N/A
1N/A # x== 0 # also: or y == 1 or y == -1
1N/A return wantarray ? ($x,$self->bzero()) : $x if $x->is_zero();
1N/A
1N/A # upgrade ?
1N/A return $upgrade->bdiv($upgrade->new($x),$y,$a,$p,$r) if defined $upgrade;
1N/A
1N/A # we need to limit the accuracy to protect against overflow
1N/A my $fallback = 0;
1N/A my (@params,$scale);
1N/A ($x,@params) = $x->_find_round_parameters($a,$p,$r,$y);
1N/A
1N/A return $x if $x->is_nan(); # error in _find_round_parameters?
1N/A
1N/A # no rounding at all, so must use fallback
1N/A if (scalar @params == 0)
1N/A {
1N/A # simulate old behaviour
1N/A $params[0] = $self->div_scale(); # and round to it as accuracy
1N/A $scale = $params[0]+4; # at least four more for proper round
1N/A $params[2] = $r; # round mode by caller or undef
1N/A $fallback = 1; # to clear a/p afterwards
1N/A }
1N/A else
1N/A {
1N/A # the 4 below is empirical, and there might be cases where it is not
1N/A # enough...
1N/A $scale = abs($params[0] || $params[1]) + 4; # take whatever is defined
1N/A }
1N/A my $lx = $MBI->_len($x->{_m}); my $ly = $MBI->_len($y->{_m});
1N/A $scale = $lx if $lx > $scale;
1N/A $scale = $ly if $ly > $scale;
1N/A my $diff = $ly - $lx;
1N/A $scale += $diff if $diff > 0; # if lx << ly, but not if ly << lx!
1N/A
1N/A # make copy of $x in case of list context for later reminder calculation
1N/A my $rem;
1N/A if (wantarray && !$y->is_one())
1N/A {
1N/A $rem = $x->copy();
1N/A }
1N/A
1N/A $x->{sign} = $x->{sign} ne $y->sign() ? '-' : '+';
1N/A
1N/A # check for / +-1 ( +/- 1E0)
1N/A if (!$y->is_one())
1N/A {
1N/A # promote BigInts and it's subclasses (except when already a BigFloat)
1N/A $y = $self->new($y) unless $y->isa('Math::BigFloat');
1N/A
1N/A # calculate the result to $scale digits and then round it
1N/A # a * 10 ** b / c * 10 ** d => a/c * 10 ** (b-d)
1N/A $MBI->_lsft($x->{_m},$MBI->_new($scale),10);
1N/A $MBI->_div ($x->{_m},$y->{_m} ); # a/c
1N/A
1N/A ($x->{_e},$x->{_es}) =
1N/A _e_sub($x->{_e}, $y->{_e}, $x->{_es}, $y->{_es});
1N/A # correct for 10**scale
1N/A ($x->{_e},$x->{_es}) =
1N/A _e_sub($x->{_e}, $MBI->_new($scale), $x->{_es}, '+');
1N/A $x->bnorm(); # remove trailing 0's
1N/A }
1N/A
1N/A # shortcut to not run through _find_round_parameters again
1N/A if (defined $params[0])
1N/A {
1N/A delete $x->{_a}; # clear before round
1N/A $x->bround($params[0],$params[2]); # then round accordingly
1N/A }
1N/A else
1N/A {
1N/A delete $x->{_p}; # clear before round
1N/A $x->bfround($params[1],$params[2]); # then round accordingly
1N/A }
1N/A if ($fallback)
1N/A {
1N/A # clear a/p after round, since user did not request it
1N/A delete $x->{_a}; delete $x->{_p};
1N/A }
1N/A
1N/A if (wantarray)
1N/A {
1N/A if (!$y->is_one())
1N/A {
1N/A $rem->bmod($y,@params); # copy already done
1N/A }
1N/A else
1N/A {
1N/A $rem = $self->bzero();
1N/A }
1N/A if ($fallback)
1N/A {
1N/A # clear a/p after round, since user did not request it
1N/A delete $rem->{_a}; delete $rem->{_p};
1N/A }
1N/A return ($x,$rem);
1N/A }
1N/A $x;
1N/A }
1N/A
1N/Asub bmod
1N/A {
1N/A # (dividend: BFLOAT or num_str, divisor: BFLOAT or num_str) return reminder
1N/A
1N/A # set up parameters
1N/A my ($self,$x,$y,$a,$p,$r) = (ref($_[0]),@_);
1N/A # objectify is costly, so avoid it
1N/A if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1])))
1N/A {
1N/A ($self,$x,$y,$a,$p,$r) = objectify(2,@_);
1N/A }
1N/A
1N/A # handle NaN, inf, -inf
1N/A if (($x->{sign} !~ /^[+-]$/) || ($y->{sign} !~ /^[+-]$/))
1N/A {
1N/A my ($d,$re) = $self->SUPER::_div_inf($x,$y);
1N/A $x->{sign} = $re->{sign};
1N/A $x->{_e} = $re->{_e};
1N/A $x->{_m} = $re->{_m};
1N/A return $x->round($a,$p,$r,$y);
1N/A }
1N/A if ($y->is_zero())
1N/A {
1N/A return $x->bnan() if $x->is_zero();
1N/A return $x;
1N/A }
1N/A return $x->bzero() if $y->is_one() || $x->is_zero();
1N/A
1N/A my $cmp = $x->bacmp($y); # equal or $x < $y?
1N/A return $x->bzero($a,$p) if $cmp == 0; # $x == $y => result 0
1N/A
1N/A # only $y of the operands negative?
1N/A my $neg = 0; $neg = 1 if $x->{sign} ne $y->{sign};
1N/A
1N/A $x->{sign} = $y->{sign}; # calc sign first
1N/A return $x->round($a,$p,$r) if $cmp < 0 && $neg == 0; # $x < $y => result $x
1N/A
1N/A my $ym = $MBI->_copy($y->{_m});
1N/A
1N/A # 2e1 => 20
1N/A $MBI->_lsft( $ym, $y->{_e}, 10)
1N/A if $y->{_es} eq '+' && !$MBI->_is_zero($y->{_e});
1N/A
1N/A # if $y has digits after dot
1N/A my $shifty = 0; # correct _e of $x by this
1N/A if ($y->{_es} eq '-') # has digits after dot
1N/A {
1N/A # 123 % 2.5 => 1230 % 25 => 5 => 0.5
1N/A $shifty = $MBI->_num($y->{_e}); # no more digits after dot
1N/A $MBI->_lsft($x->{_m}, $y->{_e}, 10);# 123 => 1230, $y->{_m} is already 25
1N/A }
1N/A # $ym is now mantissa of $y based on exponent 0
1N/A
1N/A my $shiftx = 0; # correct _e of $x by this
1N/A if ($x->{_es} eq '-') # has digits after dot
1N/A {
1N/A # 123.4 % 20 => 1234 % 200
1N/A $shiftx = $MBI->_num($x->{_e}); # no more digits after dot
1N/A $MBI->_lsft($ym, $x->{_e}, 10); # 123 => 1230
1N/A }
1N/A # 123e1 % 20 => 1230 % 20
1N/A if ($x->{_es} eq '+' && !$MBI->_is_zero($x->{_e}))
1N/A {
1N/A $MBI->_lsft( $x->{_m}, $x->{_e},10); # es => '+' here
1N/A }
1N/A
1N/A $x->{_e} = $MBI->_new($shiftx);
1N/A $x->{_es} = '+';
1N/A $x->{_es} = '-' if $shiftx != 0 || $shifty != 0;
1N/A $MBI->_add( $x->{_e}, $MBI->_new($shifty)) if $shifty != 0;
1N/A
1N/A # now mantissas are equalized, exponent of $x is adjusted, so calc result
1N/A
1N/A $x->{_m} = $MBI->_mod( $x->{_m}, $ym);
1N/A
1N/A $x->{sign} = '+' if $MBI->_is_zero($x->{_m}); # fix sign for -0
1N/A $x->bnorm();
1N/A
1N/A if ($neg != 0) # one of them negative => correct in place
1N/A {
1N/A my $r = $y - $x;
1N/A $x->{_m} = $r->{_m};
1N/A $x->{_e} = $r->{_e};
1N/A $x->{_es} = $r->{_es};
1N/A $x->{sign} = '+' if $MBI->_is_zero($x->{_m}); # fix sign for -0
1N/A $x->bnorm();
1N/A }
1N/A
1N/A $x->round($a,$p,$r,$y); # round and return
1N/A }
1N/A
1N/Asub broot
1N/A {
1N/A # calculate $y'th root of $x
1N/A
1N/A # set up parameters
1N/A my ($self,$x,$y,$a,$p,$r) = (ref($_[0]),@_);
1N/A # objectify is costly, so avoid it
1N/A if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1])))
1N/A {
1N/A ($self,$x,$y,$a,$p,$r) = objectify(2,@_);
1N/A }
1N/A
1N/A # NaN handling: $x ** 1/0, x or y NaN, or y inf/-inf or y == 0
1N/A return $x->bnan() if $x->{sign} !~ /^\+/ || $y->is_zero() ||
1N/A $y->{sign} !~ /^\+$/;
1N/A
1N/A return $x if $x->is_zero() || $x->is_one() || $x->is_inf() || $y->is_one();
1N/A
1N/A # we need to limit the accuracy to protect against overflow
1N/A my $fallback = 0;
1N/A my (@params,$scale);
1N/A ($x,@params) = $x->_find_round_parameters($a,$p,$r);
1N/A
1N/A return $x if $x->is_nan(); # error in _find_round_parameters?
1N/A
1N/A # no rounding at all, so must use fallback
1N/A if (scalar @params == 0)
1N/A {
1N/A # simulate old behaviour
1N/A $params[0] = $self->div_scale(); # and round to it as accuracy
1N/A $scale = $params[0]+4; # at least four more for proper round
1N/A $params[2] = $r; # iound mode by caller or undef
1N/A $fallback = 1; # to clear a/p afterwards
1N/A }
1N/A else
1N/A {
1N/A # the 4 below is empirical, and there might be cases where it is not
1N/A # enough...
1N/A $scale = abs($params[0] || $params[1]) + 4; # take whatever is defined
1N/A }
1N/A
1N/A # when user set globals, they would interfere with our calculation, so
1N/A # disable them and later re-enable them
1N/A no strict 'refs';
1N/A my $abr = "$self\::accuracy"; my $ab = $$abr; $$abr = undef;
1N/A my $pbr = "$self\::precision"; my $pb = $$pbr; $$pbr = undef;
1N/A # we also need to disable any set A or P on $x (_find_round_parameters took
1N/A # them already into account), since these would interfere, too
1N/A delete $x->{_a}; delete $x->{_p};
1N/A # need to disable $upgrade in BigInt, to avoid deep recursion
1N/A local $Math::BigInt::upgrade = undef; # should be really parent class vs MBI
1N/A
1N/A # remember sign and make $x positive, since -4 ** (1/2) => -2
1N/A my $sign = 0; $sign = 1 if $x->{sign} eq '-'; $x->{sign} = '+';
1N/A
1N/A my $is_two = 0;
1N/A if ($y->isa('Math::BigFloat'))
1N/A {
1N/A $is_two = ($y->{sign} eq '+' && $MBI->_is_two($y->{_m}) && $MBI->_is_zero($y->{_e}));
1N/A }
1N/A else
1N/A {
1N/A $is_two = ($y == 2);
1N/A }
1N/A
1N/A # normal square root if $y == 2:
1N/A if ($is_two)
1N/A {
1N/A $x->bsqrt($scale+4);
1N/A }
1N/A elsif ($y->is_one('-'))
1N/A {
1N/A # $x ** -1 => 1/$x
1N/A my $u = $self->bone()->bdiv($x,$scale);
1N/A # copy private parts over
1N/A $x->{_m} = $u->{_m};
1N/A $x->{_e} = $u->{_e};
1N/A $x->{_es} = $u->{_es};
1N/A }
1N/A else
1N/A {
1N/A # calculate the broot() as integer result first, and if it fits, return
1N/A # it rightaway (but only if $x and $y are integer):
1N/A
1N/A my $done = 0; # not yet
1N/A if ($y->is_int() && $x->is_int())
1N/A {
1N/A my $i = $MBI->_copy( $x->{_m} );
1N/A $MBI->_lsft( $i, $x->{_e}, 10 ) unless $MBI->_is_zero($x->{_e});
1N/A my $int = Math::BigInt->bzero();
1N/A $int->{value} = $i;
1N/A $int->broot($y->as_number());
1N/A # if ($exact)
1N/A if ($int->copy()->bpow($y) == $x)
1N/A {
1N/A # found result, return it
1N/A $x->{_m} = $int->{value};
1N/A $x->{_e} = $MBI->_zero();
1N/A $x->{_es} = '+';
1N/A $x->bnorm();
1N/A $done = 1;
1N/A }
1N/A }
1N/A if ($done == 0)
1N/A {
1N/A my $u = $self->bone()->bdiv($y,$scale+4);
1N/A delete $u->{_a}; delete $u->{_p}; # otherwise it conflicts
1N/A $x->bpow($u,$scale+4); # el cheapo
1N/A }
1N/A }
1N/A $x->bneg() if $sign == 1;
1N/A
1N/A # shortcut to not run through _find_round_parameters again
1N/A if (defined $params[0])
1N/A {
1N/A $x->bround($params[0],$params[2]); # then round accordingly
1N/A }
1N/A else
1N/A {
1N/A $x->bfround($params[1],$params[2]); # then round accordingly
1N/A }
1N/A if ($fallback)
1N/A {
1N/A # clear a/p after round, since user did not request it
1N/A delete $x->{_a}; delete $x->{_p};
1N/A }
1N/A # restore globals
1N/A $$abr = $ab; $$pbr = $pb;
1N/A $x;
1N/A }
1N/A
1N/Asub bsqrt
1N/A {
1N/A # calculate square root
1N/A my ($self,$x,$a,$p,$r) = ref($_[0]) ? (ref($_[0]),@_) : objectify(1,@_);
1N/A
1N/A return $x->bnan() if $x->{sign} !~ /^[+]/; # NaN, -inf or < 0
1N/A return $x if $x->{sign} eq '+inf'; # sqrt(inf) == inf
1N/A return $x->round($a,$p,$r) if $x->is_zero() || $x->is_one();
1N/A
1N/A # we need to limit the accuracy to protect against overflow
1N/A my $fallback = 0;
1N/A my (@params,$scale);
1N/A ($x,@params) = $x->_find_round_parameters($a,$p,$r);
1N/A
1N/A return $x if $x->is_nan(); # error in _find_round_parameters?
1N/A
1N/A # no rounding at all, so must use fallback
1N/A if (scalar @params == 0)
1N/A {
1N/A # simulate old behaviour
1N/A $params[0] = $self->div_scale(); # and round to it as accuracy
1N/A $scale = $params[0]+4; # at least four more for proper round
1N/A $params[2] = $r; # round mode by caller or undef
1N/A $fallback = 1; # to clear a/p afterwards
1N/A }
1N/A else
1N/A {
1N/A # the 4 below is empirical, and there might be cases where it is not
1N/A # enough...
1N/A $scale = abs($params[0] || $params[1]) + 4; # take whatever is defined
1N/A }
1N/A
1N/A # when user set globals, they would interfere with our calculation, so
1N/A # disable them and later re-enable them
1N/A no strict 'refs';
1N/A my $abr = "$self\::accuracy"; my $ab = $$abr; $$abr = undef;
1N/A my $pbr = "$self\::precision"; my $pb = $$pbr; $$pbr = undef;
1N/A # we also need to disable any set A or P on $x (_find_round_parameters took
1N/A # them already into account), since these would interfere, too
1N/A delete $x->{_a}; delete $x->{_p};
1N/A # need to disable $upgrade in BigInt, to avoid deep recursion
1N/A local $Math::BigInt::upgrade = undef; # should be really parent class vs MBI
1N/A
1N/A my $i = $MBI->_copy( $x->{_m} );
1N/A $MBI->_lsft( $i, $x->{_e}, 10 ) unless $MBI->_is_zero($x->{_e});
1N/A my $xas = Math::BigInt->bzero();
1N/A $xas->{value} = $i;
1N/A
1N/A my $gs = $xas->copy()->bsqrt(); # some guess
1N/A
1N/A if (($x->{_es} ne '-') # guess can't be accurate if there are
1N/A # digits after the dot
1N/A && ($xas->bacmp($gs * $gs) == 0)) # guess hit the nail on the head?
1N/A {
1N/A # exact result, copy result over to keep $x
1N/A $x->{_m} = $gs->{value}; $x->{_e} = $MBI->_zero(); $x->{_es} = '+';
1N/A $x->bnorm();
1N/A # shortcut to not run through _find_round_parameters again
1N/A if (defined $params[0])
1N/A {
1N/A $x->bround($params[0],$params[2]); # then round accordingly
1N/A }
1N/A else
1N/A {
1N/A $x->bfround($params[1],$params[2]); # then round accordingly
1N/A }
1N/A if ($fallback)
1N/A {
1N/A # clear a/p after round, since user did not request it
1N/A delete $x->{_a}; delete $x->{_p};
1N/A }
1N/A # re-enable A and P, upgrade is taken care of by "local"
1N/A ${"$self\::accuracy"} = $ab; ${"$self\::precision"} = $pb;
1N/A return $x;
1N/A }
1N/A
1N/A # sqrt(2) = 1.4 because sqrt(2*100) = 1.4*10; so we can increase the accuracy
1N/A # of the result by multipyling the input by 100 and then divide the integer
1N/A # result of sqrt(input) by 10. Rounding afterwards returns the real result.
1N/A
1N/A # The following steps will transform 123.456 (in $x) into 123456 (in $y1)
1N/A my $y1 = $MBI->_copy($x->{_m});
1N/A
1N/A my $length = $MBI->_len($y1);
1N/A
1N/A # Now calculate how many digits the result of sqrt(y1) would have
1N/A my $digits = int($length / 2);
1N/A
1N/A # But we need at least $scale digits, so calculate how many are missing
1N/A my $shift = $scale - $digits;
1N/A
1N/A # That should never happen (we take care of integer guesses above)
1N/A # $shift = 0 if $shift < 0;
1N/A
1N/A # Multiply in steps of 100, by shifting left two times the "missing" digits
1N/A my $s2 = $shift * 2;
1N/A
1N/A # We now make sure that $y1 has the same odd or even number of digits than
1N/A # $x had. So when _e of $x is odd, we must shift $y1 by one digit left,
1N/A # because we always must multiply by steps of 100 (sqrt(100) is 10) and not
1N/A # steps of 10. The length of $x does not count, since an even or odd number
1N/A # of digits before the dot is not changed by adding an even number of digits
1N/A # after the dot (the result is still odd or even digits long).
1N/A $s2++ if $MBI->_is_odd($x->{_e});
1N/A
1N/A $MBI->_lsft( $y1, $MBI->_new($s2), 10);
1N/A
1N/A # now take the square root and truncate to integer
1N/A $y1 = $MBI->_sqrt($y1);
1N/A
1N/A # By "shifting" $y1 right (by creating a negative _e) we calculate the final
1N/A # result, which is than later rounded to the desired scale.
1N/A
1N/A # calculate how many zeros $x had after the '.' (or before it, depending
1N/A # on sign of $dat, the result should have half as many:
1N/A my $dat = $MBI->_num($x->{_e});
1N/A $dat = -$dat if $x->{_es} eq '-';
1N/A $dat += $length;
1N/A
1N/A if ($dat > 0)
1N/A {
1N/A # no zeros after the dot (e.g. 1.23, 0.49 etc)
1N/A # preserve half as many digits before the dot than the input had
1N/A # (but round this "up")
1N/A $dat = int(($dat+1)/2);
1N/A }
1N/A else
1N/A {
1N/A $dat = int(($dat)/2);
1N/A }
1N/A $dat -= $MBI->_len($y1);
1N/A if ($dat < 0)
1N/A {
1N/A $dat = abs($dat);
1N/A $x->{_e} = $MBI->_new( $dat );
1N/A $x->{_es} = '-';
1N/A }
1N/A else
1N/A {
1N/A $x->{_e} = $MBI->_new( $dat );
1N/A $x->{_es} = '+';
1N/A }
1N/A $x->{_m} = $y1;
1N/A $x->bnorm();
1N/A
1N/A # shortcut to not run through _find_round_parameters again
1N/A if (defined $params[0])
1N/A {
1N/A $x->bround($params[0],$params[2]); # then round accordingly
1N/A }
1N/A else
1N/A {
1N/A $x->bfround($params[1],$params[2]); # then round accordingly
1N/A }
1N/A if ($fallback)
1N/A {
1N/A # clear a/p after round, since user did not request it
1N/A delete $x->{_a}; delete $x->{_p};
1N/A }
1N/A # restore globals
1N/A $$abr = $ab; $$pbr = $pb;
1N/A $x;
1N/A }
1N/A
1N/Asub bfac
1N/A {
1N/A # (BFLOAT or num_str, BFLOAT or num_str) return BFLOAT
1N/A # compute factorial number, modifies first argument
1N/A
1N/A # set up parameters
1N/A my ($self,$x,@r) = (ref($_[0]),@_);
1N/A # objectify is costly, so avoid it
1N/A ($self,$x,@r) = objectify(1,@_) if !ref($x);
1N/A
1N/A return $x if $x->{sign} eq '+inf'; # inf => inf
1N/A return $x->bnan()
1N/A if (($x->{sign} ne '+') || # inf, NaN, <0 etc => NaN
1N/A ($x->{_es} ne '+')); # digits after dot?
1N/A
1N/A # use BigInt's bfac() for faster calc
1N/A if (! $MBI->_is_zero($x->{_e}))
1N/A {
1N/A $MBI->_lsft($x->{_m}, $x->{_e},10); # change 12e1 to 120e0
1N/A $x->{_e} = $MBI->_zero(); # normalize
1N/A $x->{_es} = '+';
1N/A }
1N/A $MBI->_fac($x->{_m}); # calculate factorial
1N/A $x->bnorm()->round(@r); # norm again and round result
1N/A }
1N/A
1N/Asub _pow
1N/A {
1N/A # Calculate a power where $y is a non-integer, like 2 ** 0.5
1N/A my ($x,$y,$a,$p,$r) = @_;
1N/A my $self = ref($x);
1N/A
1N/A # if $y == 0.5, it is sqrt($x)
1N/A $HALF = $self->new($HALF) unless ref($HALF);
1N/A return $x->bsqrt($a,$p,$r,$y) if $y->bcmp($HALF) == 0;
1N/A
1N/A # Using:
1N/A # a ** x == e ** (x * ln a)
1N/A
1N/A # u = y * ln x
1N/A # _ _
1N/A # Taylor: | u u^2 u^3 |
1N/A # x ** y = 1 + | --- + --- + ----- + ... |
1N/A # |_ 1 1*2 1*2*3 _|
1N/A
1N/A # we need to limit the accuracy to protect against overflow
1N/A my $fallback = 0;
1N/A my ($scale,@params);
1N/A ($x,@params) = $x->_find_round_parameters($a,$p,$r);
1N/A
1N/A return $x if $x->is_nan(); # error in _find_round_parameters?
1N/A
1N/A # no rounding at all, so must use fallback
1N/A if (scalar @params == 0)
1N/A {
1N/A # simulate old behaviour
1N/A $params[0] = $self->div_scale(); # and round to it as accuracy
1N/A $params[1] = undef; # disable P
1N/A $scale = $params[0]+4; # at least four more for proper round
1N/A $params[2] = $r; # round mode by caller or undef
1N/A $fallback = 1; # to clear a/p afterwards
1N/A }
1N/A else
1N/A {
1N/A # the 4 below is empirical, and there might be cases where it is not
1N/A # enough...
1N/A $scale = abs($params[0] || $params[1]) + 4; # take whatever is defined
1N/A }
1N/A
1N/A # when user set globals, they would interfere with our calculation, so
1N/A # disable them and later re-enable them
1N/A no strict 'refs';
1N/A my $abr = "$self\::accuracy"; my $ab = $$abr; $$abr = undef;
1N/A my $pbr = "$self\::precision"; my $pb = $$pbr; $$pbr = undef;
1N/A # we also need to disable any set A or P on $x (_find_round_parameters took
1N/A # them already into account), since these would interfere, too
1N/A delete $x->{_a}; delete $x->{_p};
1N/A # need to disable $upgrade in BigInt, to avoid deep recursion
1N/A local $Math::BigInt::upgrade = undef;
1N/A
1N/A my ($limit,$v,$u,$below,$factor,$next,$over);
1N/A
1N/A $u = $x->copy()->blog(undef,$scale)->bmul($y);
1N/A $v = $self->bone(); # 1
1N/A $factor = $self->new(2); # 2
1N/A $x->bone(); # first term: 1
1N/A
1N/A $below = $v->copy();
1N/A $over = $u->copy();
1N/A
1N/A $limit = $self->new("1E-". ($scale-1));
1N/A #my $steps = 0;
1N/A while (3 < 5)
1N/A {
1N/A # we calculate the next term, and add it to the last
1N/A # when the next term is below our limit, it won't affect the outcome
1N/A # anymore, so we stop
1N/A $next = $over->copy()->bdiv($below,$scale);
1N/A last if $next->bacmp($limit) <= 0;
1N/A $x->badd($next);
1N/A # calculate things for the next term
1N/A $over *= $u; $below *= $factor; $factor->binc();
1N/A
1N/A last if $x->{sign} !~ /^[-+]$/;
1N/A
1N/A #$steps++;
1N/A }
1N/A
1N/A # shortcut to not run through _find_round_parameters again
1N/A if (defined $params[0])
1N/A {
1N/A $x->bround($params[0],$params[2]); # then round accordingly
1N/A }
1N/A else
1N/A {
1N/A $x->bfround($params[1],$params[2]); # then round accordingly
1N/A }
1N/A if ($fallback)
1N/A {
1N/A # clear a/p after round, since user did not request it
1N/A delete $x->{_a}; delete $x->{_p};
1N/A }
1N/A # restore globals
1N/A $$abr = $ab; $$pbr = $pb;
1N/A $x;
1N/A }
1N/A
1N/Asub bpow
1N/A {
1N/A # (BFLOAT or num_str, BFLOAT or num_str) return BFLOAT
1N/A # compute power of two numbers, second arg is used as integer
1N/A # modifies first argument
1N/A
1N/A # set up parameters
1N/A my ($self,$x,$y,$a,$p,$r) = (ref($_[0]),@_);
1N/A # objectify is costly, so avoid it
1N/A if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1])))
1N/A {
1N/A ($self,$x,$y,$a,$p,$r) = objectify(2,@_);
1N/A }
1N/A
1N/A return $x if $x->{sign} =~ /^[+-]inf$/;
1N/A return $x->bnan() if $x->{sign} eq $nan || $y->{sign} eq $nan;
1N/A return $x->bone() if $y->is_zero();
1N/A return $x if $x->is_one() || $y->is_one();
1N/A
1N/A return $x->_pow($y,$a,$p,$r) if !$y->is_int(); # non-integer power
1N/A
1N/A my $y1 = $y->as_number()->{value}; # make CALC
1N/A
1N/A # if ($x == -1)
1N/A if ($x->{sign} eq '-' && $MBI->_is_one($x->{_m}) && $MBI->_is_zero($x->{_e}))
1N/A {
1N/A # if $x == -1 and odd/even y => +1/-1 because +-1 ^ (+-1) => +-1
1N/A return $MBI->_is_odd($y1) ? $x : $x->babs(1);
1N/A }
1N/A if ($x->is_zero())
1N/A {
1N/A return $x->bone() if $y->is_zero();
1N/A return $x if $y->{sign} eq '+'; # 0**y => 0 (if not y <= 0)
1N/A # 0 ** -y => 1 / (0 ** y) => 1 / 0! (1 / 0 => +inf)
1N/A return $x->binf();
1N/A }
1N/A
1N/A my $new_sign = '+';
1N/A $new_sign = $y->is_odd() ? '-' : '+' if ($x->{sign} ne '+');
1N/A
1N/A # calculate $x->{_m} ** $y and $x->{_e} * $y separately (faster)
1N/A $x->{_m} = $MBI->_pow( $x->{_m}, $y1);
1N/A $MBI->_mul ($x->{_e}, $y1);
1N/A
1N/A $x->{sign} = $new_sign;
1N/A $x->bnorm();
1N/A if ($y->{sign} eq '-')
1N/A {
1N/A # modify $x in place!
1N/A my $z = $x->copy(); $x->bzero()->binc();
1N/A return $x->bdiv($z,$a,$p,$r); # round in one go (might ignore y's A!)
1N/A }
1N/A $x->round($a,$p,$r,$y);
1N/A }
1N/A
1N/A###############################################################################
1N/A# rounding functions
1N/A
1N/Asub bfround
1N/A {
1N/A # precision: round to the $Nth digit left (+$n) or right (-$n) from the '.'
1N/A # $n == 0 means round to integer
1N/A # expects and returns normalized numbers!
1N/A my $x = shift; my $self = ref($x) || $x; $x = $self->new(shift) if !ref($x);
1N/A
1N/A return $x if $x->modify('bfround');
1N/A
1N/A my ($scale,$mode) = $x->_scale_p($self->precision(),$self->round_mode(),@_);
1N/A return $x if !defined $scale; # no-op
1N/A
1N/A # never round a 0, +-inf, NaN
1N/A if ($x->is_zero())
1N/A {
1N/A $x->{_p} = $scale if !defined $x->{_p} || $x->{_p} < $scale; # -3 < -2
1N/A return $x;
1N/A }
1N/A return $x if $x->{sign} !~ /^[+-]$/;
1N/A
1N/A # don't round if x already has lower precision
1N/A return $x if (defined $x->{_p} && $x->{_p} < 0 && $scale < $x->{_p});
1N/A
1N/A $x->{_p} = $scale; # remember round in any case
1N/A delete $x->{_a}; # and clear A
1N/A if ($scale < 0)
1N/A {
1N/A # round right from the '.'
1N/A
1N/A return $x if $x->{_es} eq '+'; # e >= 0 => nothing to round
1N/A
1N/A $scale = -$scale; # positive for simplicity
1N/A my $len = $MBI->_len($x->{_m}); # length of mantissa
1N/A
1N/A # the following poses a restriction on _e, but if _e is bigger than a
1N/A # scalar, you got other problems (memory etc) anyway
1N/A my $dad = -(0+ ($x->{_es}.$MBI->_num($x->{_e}))); # digits after dot
1N/A my $zad = 0; # zeros after dot
1N/A $zad = $dad - $len if (-$dad < -$len); # for 0.00..00xxx style
1N/A
1N/A # p rint "scale $scale dad $dad zad $zad len $len\n";
1N/A # number bsstr len zad dad
1N/A # 0.123 123e-3 3 0 3
1N/A # 0.0123 123e-4 3 1 4
1N/A # 0.001 1e-3 1 2 3
1N/A # 1.23 123e-2 3 0 2
1N/A # 1.2345 12345e-4 5 0 4
1N/A
1N/A # do not round after/right of the $dad
1N/A return $x if $scale > $dad; # 0.123, scale >= 3 => exit
1N/A
1N/A # round to zero if rounding inside the $zad, but not for last zero like:
1N/A # 0.0065, scale -2, round last '0' with following '65' (scale == zad case)
1N/A return $x->bzero() if $scale < $zad;
1N/A if ($scale == $zad) # for 0.006, scale -3 and trunc
1N/A {
1N/A $scale = -$len;
1N/A }
1N/A else
1N/A {
1N/A # adjust round-point to be inside mantissa
1N/A if ($zad != 0)
1N/A {
1N/A $scale = $scale-$zad;
1N/A }
1N/A else
1N/A {
1N/A my $dbd = $len - $dad; $dbd = 0 if $dbd < 0; # digits before dot
1N/A $scale = $dbd+$scale;
1N/A }
1N/A }
1N/A }
1N/A else
1N/A {
1N/A # round left from the '.'
1N/A
1N/A # 123 => 100 means length(123) = 3 - $scale (2) => 1
1N/A
1N/A my $dbt = $MBI->_len($x->{_m});
1N/A # digits before dot
1N/A my $dbd = $dbt + ($x->{_es} . $MBI->_num($x->{_e}));
1N/A # should be the same, so treat it as this
1N/A $scale = 1 if $scale == 0;
1N/A # shortcut if already integer
1N/A return $x if $scale == 1 && $dbt <= $dbd;
1N/A # maximum digits before dot
1N/A ++$dbd;
1N/A
1N/A if ($scale > $dbd)
1N/A {
1N/A # not enough digits before dot, so round to zero
1N/A return $x->bzero;
1N/A }
1N/A elsif ( $scale == $dbd )
1N/A {
1N/A # maximum
1N/A $scale = -$dbt;
1N/A }
1N/A else
1N/A {
1N/A $scale = $dbd - $scale;
1N/A }
1N/A }
1N/A # pass sign to bround for rounding modes '+inf' and '-inf'
1N/A my $m = Math::BigInt->new( $x->{sign} . $MBI->_str($x->{_m}));
1N/A $m->bround($scale,$mode);
1N/A $x->{_m} = $m->{value}; # get our mantissa back
1N/A $x->bnorm();
1N/A }
1N/A
1N/Asub bround
1N/A {
1N/A # accuracy: preserve $N digits, and overwrite the rest with 0's
1N/A my $x = shift; my $self = ref($x) || $x; $x = $self->new(shift) if !ref($x);
1N/A
1N/A if (($_[0] || 0) < 0)
1N/A {
1N/A require Carp; Carp::croak ('bround() needs positive accuracy');
1N/A }
1N/A
1N/A my ($scale,$mode) = $x->_scale_a($self->accuracy(),$self->round_mode(),@_);
1N/A return $x if !defined $scale; # no-op
1N/A
1N/A return $x if $x->modify('bround');
1N/A
1N/A # scale is now either $x->{_a}, $accuracy, or the user parameter
1N/A # test whether $x already has lower accuracy, do nothing in this case
1N/A # but do round if the accuracy is the same, since a math operation might
1N/A # want to round a number with A=5 to 5 digits afterwards again
1N/A return $x if defined $_[0] && defined $x->{_a} && $x->{_a} < $_[0];
1N/A
1N/A # scale < 0 makes no sense
1N/A # never round a +-inf, NaN
1N/A return $x if ($scale < 0) || $x->{sign} !~ /^[+-]$/;
1N/A
1N/A # 1: $scale == 0 => keep all digits
1N/A # 2: never round a 0
1N/A # 3: if we should keep more digits than the mantissa has, do nothing
1N/A if ($scale == 0 || $x->is_zero() || $MBI->_len($x->{_m}) <= $scale)
1N/A {
1N/A $x->{_a} = $scale if !defined $x->{_a} || $x->{_a} > $scale;
1N/A return $x;
1N/A }
1N/A
1N/A # pass sign to bround for '+inf' and '-inf' rounding modes
1N/A my $m = Math::BigInt->new( $x->{sign} . $MBI->_str($x->{_m}));
1N/A
1N/A $m->bround($scale,$mode); # round mantissa
1N/A $x->{_m} = $m->{value}; # get our mantissa back
1N/A $x->{_a} = $scale; # remember rounding
1N/A delete $x->{_p}; # and clear P
1N/A $x->bnorm(); # del trailing zeros gen. by bround()
1N/A }
1N/A
1N/Asub bfloor
1N/A {
1N/A # return integer less or equal then $x
1N/A my ($self,$x,$a,$p,$r) = ref($_[0]) ? (ref($_[0]),@_) : objectify(1,@_);
1N/A
1N/A return $x if $x->modify('bfloor');
1N/A
1N/A return $x if $x->{sign} !~ /^[+-]$/; # nan, +inf, -inf
1N/A
1N/A # if $x has digits after dot
1N/A if ($x->{_es} eq '-')
1N/A {
1N/A $x->{_m} = $MBI->_rsft($x->{_m},$x->{_e},10); # cut off digits after dot
1N/A $x->{_e} = $MBI->_zero(); # trunc/norm
1N/A $x->{_es} = '+'; # abs e
1N/A $MBI->_inc($x->{_m}) if $x->{sign} eq '-'; # increment if negative
1N/A }
1N/A $x->round($a,$p,$r);
1N/A }
1N/A
1N/Asub bceil
1N/A {
1N/A # return integer greater or equal then $x
1N/A my ($self,$x,$a,$p,$r) = ref($_[0]) ? (ref($_[0]),@_) : objectify(1,@_);
1N/A
1N/A return $x if $x->modify('bceil');
1N/A return $x if $x->{sign} !~ /^[+-]$/; # nan, +inf, -inf
1N/A
1N/A # if $x has digits after dot
1N/A if ($x->{_es} eq '-')
1N/A {
1N/A $x->{_m} = $MBI->_rsft($x->{_m},$x->{_e},10); # cut off digits after dot
1N/A $x->{_e} = $MBI->_zero(); # trunc/norm
1N/A $x->{_es} = '+'; # abs e
1N/A $MBI->_inc($x->{_m}) if $x->{sign} eq '+'; # increment if positive
1N/A }
1N/A $x->round($a,$p,$r);
1N/A }
1N/A
1N/Asub brsft
1N/A {
1N/A # shift right by $y (divide by power of $n)
1N/A
1N/A # set up parameters
1N/A my ($self,$x,$y,$n,$a,$p,$r) = (ref($_[0]),@_);
1N/A # objectify is costly, so avoid it
1N/A if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1])))
1N/A {
1N/A ($self,$x,$y,$n,$a,$p,$r) = objectify(2,@_);
1N/A }
1N/A
1N/A return $x if $x->modify('brsft');
1N/A return $x if $x->{sign} !~ /^[+-]$/; # nan, +inf, -inf
1N/A
1N/A $n = 2 if !defined $n; $n = $self->new($n);
1N/A $x->bdiv($n->bpow($y),$a,$p,$r,$y);
1N/A }
1N/A
1N/Asub blsft
1N/A {
1N/A # shift left by $y (multiply by power of $n)
1N/A
1N/A # set up parameters
1N/A my ($self,$x,$y,$n,$a,$p,$r) = (ref($_[0]),@_);
1N/A # objectify is costly, so avoid it
1N/A if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1])))
1N/A {
1N/A ($self,$x,$y,$n,$a,$p,$r) = objectify(2,@_);
1N/A }
1N/A
1N/A return $x if $x->modify('blsft');
1N/A return $x if $x->{sign} !~ /^[+-]$/; # nan, +inf, -inf
1N/A
1N/A $n = 2 if !defined $n; $n = $self->new($n);
1N/A $x->bmul($n->bpow($y),$a,$p,$r,$y);
1N/A }
1N/A
1N/A###############################################################################
1N/A
1N/Asub DESTROY
1N/A {
1N/A # going through AUTOLOAD for every DESTROY is costly, avoid it by empty sub
1N/A }
1N/A
1N/Asub AUTOLOAD
1N/A {
1N/A # make fxxx and bxxx both work by selectively mapping fxxx() to MBF::bxxx()
1N/A # or falling back to MBI::bxxx()
1N/A my $name = $AUTOLOAD;
1N/A
1N/A $name =~ s/(.*):://; # split package
1N/A my $c = $1 || $class;
1N/A no strict 'refs';
1N/A $c->import() if $IMPORT == 0;
1N/A if (!method_alias($name))
1N/A {
1N/A if (!defined $name)
1N/A {
1N/A # delayed load of Carp and avoid recursion
1N/A require Carp;
1N/A Carp::croak ("$c: Can't call a method without name");
1N/A }
1N/A if (!method_hand_up($name))
1N/A {
1N/A # delayed load of Carp and avoid recursion
1N/A require Carp;
1N/A Carp::croak ("Can't call $c\-\>$name, not a valid method");
1N/A }
1N/A # try one level up, but subst. bxxx() for fxxx() since MBI only got bxxx()
1N/A $name =~ s/^f/b/;
1N/A return &{"Math::BigInt"."::$name"}(@_);
1N/A }
1N/A my $bname = $name; $bname =~ s/^f/b/;
1N/A $c .= "::$name";
1N/A *{$c} = \&{$bname};
1N/A &{$c}; # uses @_
1N/A }
1N/A
1N/Asub exponent
1N/A {
1N/A # return a copy of the exponent
1N/A my ($self,$x) = ref($_[0]) ? (ref($_[0]),$_[0]) : objectify(1,@_);
1N/A
1N/A if ($x->{sign} !~ /^[+-]$/)
1N/A {
1N/A my $s = $x->{sign}; $s =~ s/^[+-]//;
1N/A return Math::BigInt->new($s); # -inf, +inf => +inf
1N/A }
1N/A Math::BigInt->new( $x->{_es} . $MBI->_str($x->{_e}));
1N/A }
1N/A
1N/Asub mantissa
1N/A {
1N/A # return a copy of the mantissa
1N/A my ($self,$x) = ref($_[0]) ? (ref($_[0]),$_[0]) : objectify(1,@_);
1N/A
1N/A if ($x->{sign} !~ /^[+-]$/)
1N/A {
1N/A my $s = $x->{sign}; $s =~ s/^[+]//;
1N/A return Math::BigInt->new($s); # -inf, +inf => +inf
1N/A }
1N/A my $m = Math::BigInt->new( $MBI->_str($x->{_m}));
1N/A $m->bneg() if $x->{sign} eq '-';
1N/A
1N/A $m;
1N/A }
1N/A
1N/Asub parts
1N/A {
1N/A # return a copy of both the exponent and the mantissa
1N/A my ($self,$x) = ref($_[0]) ? (ref($_[0]),$_[0]) : objectify(1,@_);
1N/A
1N/A if ($x->{sign} !~ /^[+-]$/)
1N/A {
1N/A my $s = $x->{sign}; $s =~ s/^[+]//; my $se = $s; $se =~ s/^[-]//;
1N/A return ($self->new($s),$self->new($se)); # +inf => inf and -inf,+inf => inf
1N/A }
1N/A my $m = Math::BigInt->bzero();
1N/A $m->{value} = $MBI->_copy($x->{_m});
1N/A $m->bneg() if $x->{sign} eq '-';
1N/A ($m, Math::BigInt->new( $x->{_es} . $MBI->_num($x->{_e}) ));
1N/A }
1N/A
1N/A##############################################################################
1N/A# private stuff (internal use only)
1N/A
1N/Asub import
1N/A {
1N/A my $self = shift;
1N/A my $l = scalar @_;
1N/A my $lib = ''; my @a;
1N/A $IMPORT=1;
1N/A for ( my $i = 0; $i < $l ; $i++)
1N/A {
1N/A if ( $_[$i] eq ':constant' )
1N/A {
1N/A # This causes overlord er load to step in. 'binary' and 'integer'
1N/A # are handled by BigInt.
1N/A overload::constant float => sub { $self->new(shift); };
1N/A }
1N/A elsif ($_[$i] eq 'upgrade')
1N/A {
1N/A # this causes upgrading
1N/A $upgrade = $_[$i+1]; # or undef to disable
1N/A $i++;
1N/A }
1N/A elsif ($_[$i] eq 'downgrade')
1N/A {
1N/A # this causes downgrading
1N/A $downgrade = $_[$i+1]; # or undef to disable
1N/A $i++;
1N/A }
1N/A elsif ($_[$i] eq 'lib')
1N/A {
1N/A # alternative library
1N/A $lib = $_[$i+1] || ''; # default Calc
1N/A $i++;
1N/A }
1N/A elsif ($_[$i] eq 'with')
1N/A {
1N/A # alternative class for our private parts()
1N/A # XXX: no longer supported
1N/A # $MBI = $_[$i+1] || 'Math::BigInt';
1N/A $i++;
1N/A }
1N/A else
1N/A {
1N/A push @a, $_[$i];
1N/A }
1N/A }
1N/A
1N/A # let use Math::BigInt lib => 'GMP'; use Math::BigFloat; still work
1N/A my $mbilib = eval { Math::BigInt->config()->{lib} };
1N/A if ((defined $mbilib) && ($MBI eq 'Math::BigInt::Calc'))
1N/A {
1N/A # MBI already loaded
1N/A Math::BigInt->import('lib',"$lib,$mbilib", 'objectify');
1N/A }
1N/A else
1N/A {
1N/A # MBI not loaded, or with ne "Math::BigInt::Calc"
1N/A $lib .= ",$mbilib" if defined $mbilib;
1N/A $lib =~ s/^,//; # don't leave empty
1N/A # replacement library can handle lib statement, but also could ignore it
1N/A if ($] < 5.006)
1N/A {
1N/A # Perl < 5.6.0 dies with "out of memory!" when eval() and ':constant' is
1N/A # used in the same script, or eval inside import().
1N/A require Math::BigInt;
1N/A Math::BigInt->import( lib => $lib, 'objectify' );
1N/A }
1N/A else
1N/A {
1N/A my $rc = "use Math::BigInt lib => '$lib', 'objectify';";
1N/A eval $rc;
1N/A }
1N/A }
1N/A if ($@)
1N/A {
1N/A require Carp; Carp::croak ("Couldn't load $lib: $! $@");
1N/A }
1N/A $MBI = Math::BigInt->config()->{lib};
1N/A
1N/A # any non :constant stuff is handled by our parent, Exporter
1N/A # even if @_ is empty, to give it a chance
1N/A $self->SUPER::import(@a); # for subclasses
1N/A $self->export_to_level(1,$self,@a); # need this, too
1N/A }
1N/A
1N/Asub bnorm
1N/A {
1N/A # adjust m and e so that m is smallest possible
1N/A # round number according to accuracy and precision settings
1N/A my ($self,$x) = ref($_[0]) ? (undef,$_[0]) : objectify(1,@_);
1N/A
1N/A return $x if $x->{sign} !~ /^[+-]$/; # inf, nan etc
1N/A
1N/A my $zeros = $MBI->_zeros($x->{_m}); # correct for trailing zeros
1N/A if ($zeros != 0)
1N/A {
1N/A my $z = $MBI->_new($zeros);
1N/A $x->{_m} = $MBI->_rsft ($x->{_m}, $z, 10);
1N/A if ($x->{_es} eq '-')
1N/A {
1N/A if ($MBI->_acmp($x->{_e},$z) >= 0)
1N/A {
1N/A $x->{_e} = $MBI->_sub ($x->{_e}, $z);
1N/A $x->{_es} = '+' if $MBI->_is_zero($x->{_e});
1N/A }
1N/A else
1N/A {
1N/A $x->{_e} = $MBI->_sub ( $MBI->_copy($z), $x->{_e});
1N/A $x->{_es} = '+';
1N/A }
1N/A }
1N/A else
1N/A {
1N/A $x->{_e} = $MBI->_add ($x->{_e}, $z);
1N/A }
1N/A }
1N/A else
1N/A {
1N/A # $x can only be 0Ey if there are no trailing zeros ('0' has 0 trailing
1N/A # zeros). So, for something like 0Ey, set y to 1, and -0 => +0
1N/A $x->{sign} = '+', $x->{_es} = '+', $x->{_e} = $MBI->_one()
1N/A if $MBI->_is_zero($x->{_m});
1N/A }
1N/A
1N/A $x; # MBI bnorm is no-op, so dont call it
1N/A }
1N/A
1N/A##############################################################################
1N/A
1N/Asub as_hex
1N/A {
1N/A # return number as hexadecimal string (only for integers defined)
1N/A my ($self,$x) = ref($_[0]) ? (ref($_[0]),$_[0]) : objectify(1,@_);
1N/A
1N/A return $x->bstr() if $x->{sign} !~ /^[+-]$/; # inf, nan etc
1N/A return '0x0' if $x->is_zero();
1N/A
1N/A return $nan if $x->{_es} ne '+'; # how to do 1e-1 in hex!?
1N/A
1N/A my $z = $MBI->_copy($x->{_m});
1N/A if (! $MBI->_is_zero($x->{_e})) # > 0
1N/A {
1N/A $MBI->_lsft( $z, $x->{_e},10);
1N/A }
1N/A $z = Math::BigInt->new( $x->{sign} . $MBI->_num($z));
1N/A $z->as_hex();
1N/A }
1N/A
1N/Asub as_bin
1N/A {
1N/A # return number as binary digit string (only for integers defined)
1N/A my ($self,$x) = ref($_[0]) ? (ref($_[0]),$_[0]) : objectify(1,@_);
1N/A
1N/A return $x->bstr() if $x->{sign} !~ /^[+-]$/; # inf, nan etc
1N/A return '0b0' if $x->is_zero();
1N/A
1N/A return $nan if $x->{_es} ne '+'; # how to do 1e-1 in hex!?
1N/A
1N/A my $z = $MBI->_copy($x->{_m});
1N/A if (! $MBI->_is_zero($x->{_e})) # > 0
1N/A {
1N/A $MBI->_lsft( $z, $x->{_e},10);
1N/A }
1N/A $z = Math::BigInt->new( $x->{sign} . $MBI->_num($z));
1N/A $z->as_bin();
1N/A }
1N/A
1N/Asub as_number
1N/A {
1N/A # return copy as a bigint representation of this BigFloat number
1N/A my ($self,$x) = ref($_[0]) ? (ref($_[0]),$_[0]) : objectify(1,@_);
1N/A
1N/A my $z = $MBI->_copy($x->{_m});
1N/A if ($x->{_es} eq '-') # < 0
1N/A {
1N/A $MBI->_rsft( $z, $x->{_e},10);
1N/A }
1N/A elsif (! $MBI->_is_zero($x->{_e})) # > 0
1N/A {
1N/A $MBI->_lsft( $z, $x->{_e},10);
1N/A }
1N/A $z = Math::BigInt->new( $x->{sign} . $MBI->_num($z));
1N/A $z;
1N/A }
1N/A
1N/Asub length
1N/A {
1N/A my $x = shift;
1N/A my $class = ref($x) || $x;
1N/A $x = $class->new(shift) unless ref($x);
1N/A
1N/A return 1 if $MBI->_is_zero($x->{_m});
1N/A
1N/A my $len = $MBI->_len($x->{_m});
1N/A $len += $MBI->_num($x->{_e}) if $x->{_es} eq '+';
1N/A if (wantarray())
1N/A {
1N/A my $t = 0;
1N/A $t = $MBI->_num($x->{_e}) if $x->{_es} eq '-';
1N/A return ($len, $t);
1N/A }
1N/A $len;
1N/A }
1N/A
1N/A1;
1N/A__END__
1N/A
1N/A=head1 NAME
1N/A
1N/AMath::BigFloat - Arbitrary size floating point math package
1N/A
1N/A=head1 SYNOPSIS
1N/A
1N/A use Math::BigFloat;
1N/A
1N/A # Number creation
1N/A $x = Math::BigFloat->new($str); # defaults to 0
1N/A $nan = Math::BigFloat->bnan(); # create a NotANumber
1N/A $zero = Math::BigFloat->bzero(); # create a +0
1N/A $inf = Math::BigFloat->binf(); # create a +inf
1N/A $inf = Math::BigFloat->binf('-'); # create a -inf
1N/A $one = Math::BigFloat->bone(); # create a +1
1N/A $one = Math::BigFloat->bone('-'); # create a -1
1N/A
1N/A # Testing
1N/A $x->is_zero(); # true if arg is +0
1N/A $x->is_nan(); # true if arg is NaN
1N/A $x->is_one(); # true if arg is +1
1N/A $x->is_one('-'); # true if arg is -1
1N/A $x->is_odd(); # true if odd, false for even
1N/A $x->is_even(); # true if even, false for odd
1N/A $x->is_pos(); # true if >= 0
1N/A $x->is_neg(); # true if < 0
1N/A $x->is_inf(sign); # true if +inf, or -inf (default is '+')
1N/A
1N/A $x->bcmp($y); # compare numbers (undef,<0,=0,>0)
1N/A $x->bacmp($y); # compare absolutely (undef,<0,=0,>0)
1N/A $x->sign(); # return the sign, either +,- or NaN
1N/A $x->digit($n); # return the nth digit, counting from right
1N/A $x->digit(-$n); # return the nth digit, counting from left
1N/A
1N/A # The following all modify their first argument. If you want to preserve
1N/A # $x, use $z = $x->copy()->bXXX($y); See under L<CAVEATS> for why this is
1N/A # neccessary when mixing $a = $b assigments with non-overloaded math.
1N/A
1N/A # set
1N/A $x->bzero(); # set $i to 0
1N/A $x->bnan(); # set $i to NaN
1N/A $x->bone(); # set $x to +1
1N/A $x->bone('-'); # set $x to -1
1N/A $x->binf(); # set $x to inf
1N/A $x->binf('-'); # set $x to -inf
1N/A
1N/A $x->bneg(); # negation
1N/A $x->babs(); # absolute value
1N/A $x->bnorm(); # normalize (no-op)
1N/A $x->bnot(); # two's complement (bit wise not)
1N/A $x->binc(); # increment x by 1
1N/A $x->bdec(); # decrement x by 1
1N/A
1N/A $x->badd($y); # addition (add $y to $x)
1N/A $x->bsub($y); # subtraction (subtract $y from $x)
1N/A $x->bmul($y); # multiplication (multiply $x by $y)
1N/A $x->bdiv($y); # divide, set $x to quotient
1N/A # return (quo,rem) or quo if scalar
1N/A
1N/A $x->bmod($y); # modulus ($x % $y)
1N/A $x->bpow($y); # power of arguments ($x ** $y)
1N/A $x->blsft($y); # left shift
1N/A $x->brsft($y); # right shift
1N/A # return (quo,rem) or quo if scalar
1N/A
1N/A $x->blog(); # logarithm of $x to base e (Euler's number)
1N/A $x->blog($base); # logarithm of $x to base $base (f.i. 2)
1N/A
1N/A $x->band($y); # bit-wise and
1N/A $x->bior($y); # bit-wise inclusive or
1N/A $x->bxor($y); # bit-wise exclusive or
1N/A $x->bnot(); # bit-wise not (two's complement)
1N/A
1N/A $x->bsqrt(); # calculate square-root
1N/A $x->broot($y); # $y'th root of $x (e.g. $y == 3 => cubic root)
1N/A $x->bfac(); # factorial of $x (1*2*3*4*..$x)
1N/A
1N/A $x->bround($N); # accuracy: preserve $N digits
1N/A $x->bfround($N); # precision: round to the $Nth digit
1N/A
1N/A $x->bfloor(); # return integer less or equal than $x
1N/A $x->bceil(); # return integer greater or equal than $x
1N/A
1N/A # The following do not modify their arguments:
1N/A
1N/A bgcd(@values); # greatest common divisor
1N/A blcm(@values); # lowest common multiplicator
1N/A
1N/A $x->bstr(); # return string
1N/A $x->bsstr(); # return string in scientific notation
1N/A
1N/A $x->as_int(); # return $x as BigInt
1N/A $x->exponent(); # return exponent as BigInt
1N/A $x->mantissa(); # return mantissa as BigInt
1N/A $x->parts(); # return (mantissa,exponent) as BigInt
1N/A
1N/A $x->length(); # number of digits (w/o sign and '.')
1N/A ($l,$f) = $x->length(); # number of digits, and length of fraction
1N/A
1N/A $x->precision(); # return P of $x (or global, if P of $x undef)
1N/A $x->precision($n); # set P of $x to $n
1N/A $x->accuracy(); # return A of $x (or global, if A of $x undef)
1N/A $x->accuracy($n); # set A $x to $n
1N/A
1N/A # these get/set the appropriate global value for all BigFloat objects
1N/A Math::BigFloat->precision(); # Precision
1N/A Math::BigFloat->accuracy(); # Accuracy
1N/A Math::BigFloat->round_mode(); # rounding mode
1N/A
1N/A=head1 DESCRIPTION
1N/A
1N/AAll operators (inlcuding basic math operations) are overloaded if you
1N/Adeclare your big floating point numbers as
1N/A
1N/A $i = new Math::BigFloat '12_3.456_789_123_456_789E-2';
1N/A
1N/AOperations with overloaded operators preserve the arguments, which is
1N/Aexactly what you expect.
1N/A
1N/A=head2 Canonical notation
1N/A
1N/AInput to these routines are either BigFloat objects, or strings of the
1N/Afollowing four forms:
1N/A
1N/A=over 2
1N/A
1N/A=item *
1N/A
1N/AC</^[+-]\d+$/>
1N/A
1N/A=item *
1N/A
1N/AC</^[+-]\d+\.\d*$/>
1N/A
1N/A=item *
1N/A
1N/AC</^[+-]\d+E[+-]?\d+$/>
1N/A
1N/A=item *
1N/A
1N/AC</^[+-]\d*\.\d+E[+-]?\d+$/>
1N/A
1N/A=back
1N/A
1N/Aall with optional leading and trailing zeros and/or spaces. Additonally,
1N/Anumbers are allowed to have an underscore between any two digits.
1N/A
1N/AEmpty strings as well as other illegal numbers results in 'NaN'.
1N/A
1N/Abnorm() on a BigFloat object is now effectively a no-op, since the numbers
1N/Aare always stored in normalized form. On a string, it creates a BigFloat
1N/Aobject.
1N/A
1N/A=head2 Output
1N/A
1N/AOutput values are BigFloat objects (normalized), except for bstr() and bsstr().
1N/A
1N/AThe string output will always have leading and trailing zeros stripped and drop
1N/Aa plus sign. C<bstr()> will give you always the form with a decimal point,
1N/Awhile C<bsstr()> (s for scientific) gives you the scientific notation.
1N/A
1N/A Input bstr() bsstr()
1N/A '-0' '0' '0E1'
1N/A ' -123 123 123' '-123123123' '-123123123E0'
1N/A '00.0123' '0.0123' '123E-4'
1N/A '123.45E-2' '1.2345' '12345E-4'
1N/A '10E+3' '10000' '1E4'
1N/A
1N/ASome routines (C<is_odd()>, C<is_even()>, C<is_zero()>, C<is_one()>,
1N/AC<is_nan()>) return true or false, while others (C<bcmp()>, C<bacmp()>)
1N/Areturn either undef, <0, 0 or >0 and are suited for sort.
1N/A
1N/AActual math is done by using the class defined with C<with => Class;> (which
1N/Adefaults to BigInts) to represent the mantissa and exponent.
1N/A
1N/AThe sign C</^[+-]$/> is stored separately. The string 'NaN' is used to
1N/Arepresent the result when input arguments are not numbers, as well as
1N/Athe result of dividing by zero.
1N/A
1N/A=head2 C<mantissa()>, C<exponent()> and C<parts()>
1N/A
1N/AC<mantissa()> and C<exponent()> return the said parts of the BigFloat
1N/Aas BigInts such that:
1N/A
1N/A $m = $x->mantissa();
1N/A $e = $x->exponent();
1N/A $y = $m * ( 10 ** $e );
1N/A print "ok\n" if $x == $y;
1N/A
1N/AC<< ($m,$e) = $x->parts(); >> is just a shortcut giving you both of them.
1N/A
1N/AA zero is represented and returned as C<0E1>, B<not> C<0E0> (after Knuth).
1N/A
1N/ACurrently the mantissa is reduced as much as possible, favouring higher
1N/Aexponents over lower ones (e.g. returning 1e7 instead of 10e6 or 10000000e0).
1N/AThis might change in the future, so do not depend on it.
1N/A
1N/A=head2 Accuracy vs. Precision
1N/A
1N/ASee also: L<Rounding|Rounding>.
1N/A
1N/AMath::BigFloat supports both precision and accuracy. For a full documentation,
1N/Aexamples and tips on these topics please see the large section in
1N/AL<Math::BigInt>.
1N/A
1N/ASince things like sqrt(2) or 1/3 must presented with a limited precision lest
1N/Aa operation consumes all resources, each operation produces no more than
1N/Athe requested number of digits.
1N/A
1N/APlease refer to BigInt's documentation for the precedence rules of which
1N/Aaccuracy/precision setting will be used.
1N/A
1N/AIf there is no gloabl precision set, B<and> the operation inquestion was not
1N/Acalled with a requested precision or accuracy, B<and> the input $x has no
1N/Aaccuracy or precision set, then a fallback parameter will be used. For
1N/Ahistorical reasons, it is called C<div_scale> and can be accessed via:
1N/A
1N/A $d = Math::BigFloat->div_scale(); # query
1N/A Math::BigFloat->div_scale($n); # set to $n digits
1N/A
1N/AThe default value is 40 digits.
1N/A
1N/AIn case the result of one operation has more precision than specified,
1N/Ait is rounded. The rounding mode taken is either the default mode, or the one
1N/Asupplied to the operation after the I<scale>:
1N/A
1N/A $x = Math::BigFloat->new(2);
1N/A Math::BigFloat->precision(5); # 5 digits max
1N/A $y = $x->copy()->bdiv(3); # will give 0.66666
1N/A $y = $x->copy()->bdiv(3,6); # will give 0.666666
1N/A $y = $x->copy()->bdiv(3,6,'odd'); # will give 0.666667
1N/A Math::BigFloat->round_mode('zero');
1N/A $y = $x->copy()->bdiv(3,6); # will give 0.666666
1N/A
1N/A=head2 Rounding
1N/A
1N/A=over 2
1N/A
1N/A=item ffround ( +$scale )
1N/A
1N/ARounds to the $scale'th place left from the '.', counting from the dot.
1N/AThe first digit is numbered 1.
1N/A
1N/A=item ffround ( -$scale )
1N/A
1N/ARounds to the $scale'th place right from the '.', counting from the dot.
1N/A
1N/A=item ffround ( 0 )
1N/A
1N/ARounds to an integer.
1N/A
1N/A=item fround ( +$scale )
1N/A
1N/APreserves accuracy to $scale digits from the left (aka significant digits)
1N/Aand pads the rest with zeros. If the number is between 1 and -1, the
1N/Asignificant digits count from the first non-zero after the '.'
1N/A
1N/A=item fround ( -$scale ) and fround ( 0 )
1N/A
1N/AThese are effectively no-ops.
1N/A
1N/A=back
1N/A
1N/AAll rounding functions take as a second parameter a rounding mode from one of
1N/Athe following: 'even', 'odd', '+inf', '-inf', 'zero' or 'trunc'.
1N/A
1N/AThe default rounding mode is 'even'. By using
1N/AC<< Math::BigFloat->round_mode($round_mode); >> you can get and set the default
1N/Amode for subsequent rounding. The usage of C<$Math::BigFloat::$round_mode> is
1N/Ano longer supported.
1N/AThe second parameter to the round functions then overrides the default
1N/Atemporarily.
1N/A
1N/AThe C<as_number()> function returns a BigInt from a Math::BigFloat. It uses
1N/A'trunc' as rounding mode to make it equivalent to:
1N/A
1N/A $x = 2.5;
1N/A $y = int($x) + 2;
1N/A
1N/AYou can override this by passing the desired rounding mode as parameter to
1N/AC<as_number()>:
1N/A
1N/A $x = Math::BigFloat->new(2.5);
1N/A $y = $x->as_number('odd'); # $y = 3
1N/A
1N/A=head1 EXAMPLES
1N/A
1N/A # not ready yet
1N/A
1N/A=head1 Autocreating constants
1N/A
1N/AAfter C<use Math::BigFloat ':constant'> all the floating point constants
1N/Ain the given scope are converted to C<Math::BigFloat>. This conversion
1N/Ahappens at compile time.
1N/A
1N/AIn particular
1N/A
1N/A perl -MMath::BigFloat=:constant -e 'print 2E-100,"\n"'
1N/A
1N/Aprints the value of C<2E-100>. Note that without conversion of
1N/Aconstants the expression 2E-100 will be calculated as normal floating point
1N/Anumber.
1N/A
1N/APlease note that ':constant' does not affect integer constants, nor binary
1N/Anor hexadecimal constants. Use L<bignum> or L<Math::BigInt> to get this to
1N/Awork.
1N/A
1N/A=head2 Math library
1N/A
1N/AMath with the numbers is done (by default) by a module called
1N/AMath::BigInt::Calc. This is equivalent to saying:
1N/A
1N/A use Math::BigFloat lib => 'Calc';
1N/A
1N/AYou can change this by using:
1N/A
1N/A use Math::BigFloat lib => 'BitVect';
1N/A
1N/AThe following would first try to find Math::BigInt::Foo, then
1N/AMath::BigInt::Bar, and when this also fails, revert to Math::BigInt::Calc:
1N/A
1N/A use Math::BigFloat lib => 'Foo,Math::BigInt::Bar';
1N/A
1N/ACalc.pm uses as internal format an array of elements of some decimal base
1N/A(usually 1e7, but this might be differen for some systems) with the least
1N/Asignificant digit first, while BitVect.pm uses a bit vector of base 2, most
1N/Asignificant bit first. Other modules might use even different means of
1N/Arepresenting the numbers. See the respective module documentation for further
1N/Adetails.
1N/A
1N/APlease note that Math::BigFloat does B<not> use the denoted library itself,
1N/Abut it merely passes the lib argument to Math::BigInt. So, instead of the need
1N/Ato do:
1N/A
1N/A use Math::BigInt lib => 'GMP';
1N/A use Math::BigFloat;
1N/A
1N/Ayou can roll it all into one line:
1N/A
1N/A use Math::BigFloat lib => 'GMP';
1N/A
1N/AIt is also possible to just require Math::BigFloat:
1N/A
1N/A require Math::BigFloat;
1N/A
1N/AThis will load the neccessary things (like BigInt) when they are needed, and
1N/Aautomatically.
1N/A
1N/AUse the lib, Luke! And see L<Using Math::BigInt::Lite> for more details than
1N/Ayou ever wanted to know about loading a different library.
1N/A
1N/A=head2 Using Math::BigInt::Lite
1N/A
1N/AIt is possible to use L<Math::BigInt::Lite> with Math::BigFloat:
1N/A
1N/A # 1
1N/A use Math::BigFloat with => 'Math::BigInt::Lite';
1N/A
1N/AThere is no need to "use Math::BigInt" or "use Math::BigInt::Lite", but you
1N/Acan combine these if you want. For instance, you may want to use
1N/AMath::BigInt objects in your main script, too.
1N/A
1N/A # 2
1N/A use Math::BigInt;
1N/A use Math::BigFloat with => 'Math::BigInt::Lite';
1N/A
1N/AOf course, you can combine this with the C<lib> parameter.
1N/A
1N/A # 3
1N/A use Math::BigFloat with => 'Math::BigInt::Lite', lib => 'GMP,Pari';
1N/A
1N/AThere is no need for a "use Math::BigInt;" statement, even if you want to
1N/Ause Math::BigInt's, since Math::BigFloat will needs Math::BigInt and thus
1N/Aalways loads it. But if you add it, add it B<before>:
1N/A
1N/A # 4
1N/A use Math::BigInt;
1N/A use Math::BigFloat with => 'Math::BigInt::Lite', lib => 'GMP,Pari';
1N/A
1N/ANotice that the module with the last C<lib> will "win" and thus
1N/Ait's lib will be used if the lib is available:
1N/A
1N/A # 5
1N/A use Math::BigInt lib => 'Bar,Baz';
1N/A use Math::BigFloat with => 'Math::BigInt::Lite', lib => 'Foo';
1N/A
1N/AThat would try to load Foo, Bar, Baz and Calc (in that order). Or in other
1N/Awords, Math::BigFloat will try to retain previously loaded libs when you
1N/Adon't specify it onem but if you specify one, it will try to load them.
1N/A
1N/AActually, the lib loading order would be "Bar,Baz,Calc", and then
1N/A"Foo,Bar,Baz,Calc", but independend of which lib exists, the result is the
1N/Asame as trying the latter load alone, except for the fact that one of Bar or
1N/ABaz might be loaded needlessly in an intermidiate step (and thus hang around
1N/Aand waste memory). If neither Bar nor Baz exist (or don't work/compile), they
1N/Awill still be tried to be loaded, but this is not as time/memory consuming as
1N/Aactually loading one of them. Still, this type of usage is not recommended due
1N/Ato these issues.
1N/A
1N/AThe old way (loading the lib only in BigInt) still works though:
1N/A
1N/A # 6
1N/A use Math::BigInt lib => 'Bar,Baz';
1N/A use Math::BigFloat;
1N/A
1N/AYou can even load Math::BigInt afterwards:
1N/A
1N/A # 7
1N/A use Math::BigFloat;
1N/A use Math::BigInt lib => 'Bar,Baz';
1N/A
1N/ABut this has the same problems like #5, it will first load Calc
1N/A(Math::BigFloat needs Math::BigInt and thus loads it) and then later Bar or
1N/ABaz, depending on which of them works and is usable/loadable. Since this
1N/Aloads Calc unnecc., it is not recommended.
1N/A
1N/ASince it also possible to just require Math::BigFloat, this poses the question
1N/Aabout what libary this will use:
1N/A
1N/A require Math::BigFloat;
1N/A my $x = Math::BigFloat->new(123); $x += 123;
1N/A
1N/AIt will use Calc. Please note that the call to import() is still done, but
1N/Aonly when you use for the first time some Math::BigFloat math (it is triggered
1N/Avia any constructor, so the first time you create a Math::BigFloat, the load
1N/Awill happen in the background). This means:
1N/A
1N/A require Math::BigFloat;
1N/A Math::BigFloat->import ( lib => 'Foo,Bar' );
1N/A
1N/Awould be the same as:
1N/A
1N/A use Math::BigFloat lib => 'Foo, Bar';
1N/A
1N/ABut don't try to be clever to insert some operations in between:
1N/A
1N/A require Math::BigFloat;
1N/A my $x = Math::BigFloat->bone() + 4; # load BigInt and Calc
1N/A Math::BigFloat->import( lib => 'Pari' ); # load Pari, too
1N/A $x = Math::BigFloat->bone()+4; # now use Pari
1N/A
1N/AWhile this works, it loads Calc needlessly. But maybe you just wanted that?
1N/A
1N/AB<Examples #3 is highly recommended> for daily usage.
1N/A
1N/A=head1 BUGS
1N/A
1N/APlease see the file BUGS in the CPAN distribution Math::BigInt for known bugs.
1N/A
1N/A=head1 CAVEATS
1N/A
1N/A=over 1
1N/A
1N/A=item stringify, bstr()
1N/A
1N/ABoth stringify and bstr() now drop the leading '+'. The old code would return
1N/A'+1.23', the new returns '1.23'. See the documentation in L<Math::BigInt> for
1N/Areasoning and details.
1N/A
1N/A=item bdiv
1N/A
1N/AThe following will probably not do what you expect:
1N/A
1N/A print $c->bdiv(123.456),"\n";
1N/A
1N/AIt prints both quotient and reminder since print works in list context. Also,
1N/Abdiv() will modify $c, so be carefull. You probably want to use
1N/A
1N/A print $c / 123.456,"\n";
1N/A print scalar $c->bdiv(123.456),"\n"; # or if you want to modify $c
1N/A
1N/Ainstead.
1N/A
1N/A=item Modifying and =
1N/A
1N/ABeware of:
1N/A
1N/A $x = Math::BigFloat->new(5);
1N/A $y = $x;
1N/A
1N/AIt will not do what you think, e.g. making a copy of $x. Instead it just makes
1N/Aa second reference to the B<same> object and stores it in $y. Thus anything
1N/Athat modifies $x will modify $y (except overloaded math operators), and vice
1N/Aversa. See L<Math::BigInt> for details and how to avoid that.
1N/A
1N/A=item bpow
1N/A
1N/AC<bpow()> now modifies the first argument, unlike the old code which left
1N/Ait alone and only returned the result. This is to be consistent with
1N/AC<badd()> etc. The first will modify $x, the second one won't:
1N/A
1N/A print bpow($x,$i),"\n"; # modify $x
1N/A print $x->bpow($i),"\n"; # ditto
1N/A print $x ** $i,"\n"; # leave $x alone
1N/A
1N/A=back
1N/A
1N/A=head1 SEE ALSO
1N/A
1N/AL<Math::BigInt>, L<Math::BigRat> and L<Math::Big> as well as
1N/AL<Math::BigInt::BitVect>, L<Math::BigInt::Pari> and L<Math::BigInt::GMP>.
1N/A
1N/AThe pragmas L<bignum>, L<bigint> and L<bigrat> might also be of interest
1N/Abecause they solve the autoupgrading/downgrading issue, at least partly.
1N/A
1N/AThe package at
1N/AL<http://search.cpan.org/search?mode=module&query=Math%3A%3ABigInt> contains
1N/Amore documentation including a full version history, testcases, empty
1N/Asubclass files and benchmarks.
1N/A
1N/A=head1 LICENSE
1N/A
1N/AThis program is free software; you may redistribute it and/or modify it under
1N/Athe same terms as Perl itself.
1N/A
1N/A=head1 AUTHORS
1N/A
1N/AMark Biggar, overloaded interface by Ilya Zakharevich.
1N/ACompletely rewritten by Tels http://bloodgate.com in 2001, 2002, and still
1N/Aat it in 2003.
1N/A
1N/A=cut