BigFloat.pm revision 7c478bd95313f5f23a4c958a745db2134aa03244
#
# Mike grinned. 'Two down, infinity to go' - Mike Nostrus in 'Before and After'
#
# The following hash values are internally used:
# _e : exponent (ref to $CALC object)
# _m : mantissa (ref to $CALC object)
# _es : sign of _e
# sign : +,-,+inf,-inf, or "NaN" if not a number
# _a : accuracy
# _p : precision
$VERSION = '1.44';
require 5.005;
require Exporter;
use strict;
# $_trap_inf and $_trap_nan are internal and should never be accessed from the outside
my $class = "Math::BigFloat";
use overload
'<=>' => sub { $_[2] ?
;
##############################################################################
# global constants, flags and assorted stuff
# the following are public, but their usage is not recommended. Use the
# accessor methods instead.
# class constants, use Class->constant_name() to access
$accuracy = undef;
$precision = undef;
$div_scale = 40;
$upgrade = undef;
$downgrade = undef;
# the package we are using for our private parts, defaults to:
# Math::BigInt->config()->{lib}
my $MBI = 'Math::BigInt::Calc';
# are NaNs ok? (otherwise it dies when encountering an NaN) set w/ config()
$_trap_nan = 0;
# the same for infinity
$_trap_inf = 0;
# constant for easier life
my $nan = 'NaN';
# some digits of accuracy for blog(undef,10); which we use in blog() for speed
my $LOG_10 =
'2.3025850929940456840179914546843642076011014886287729760333279009675726097';
# ditto for log(2)
my $LOG_2 =
'0.6931471805599453094172321214581765680755001343602552541206800094933936220';
##############################################################################
# the old code had $rnd_mode, so we need to support it, too
sub FETCH { return $round_mode; }
BEGIN
{
# when someone set's $rnd_mode, we catch this and check the value to see
# whether it is valid or not.
}
##############################################################################
{
# valid method aliases for AUTOLOAD
my %methods = map { $_ => 1 }
/;
# valid method's that can be hand-ed up (for AUTOLOAD)
my %hand_ups = map { $_ => 1 }
/;
}
##############################################################################
# constructors
sub new
{
# create a new BigFloat object from a string or another bigfloat object.
# _e: exponent
# _m: mantissa
# sign => sign (+/-), or "NaN"
# avoid numify-calls by not using || on $wanted!
# shortcut for bigints and its subclasses
{
}
# got string
# handle '+inf', '-inf' first
{
}
if (!ref $mis)
{
if ($_trap_nan)
{
require Carp;
Carp::croak ("$wanted is not a number initialized to $class");
}
}
else
{
# make integer from mantissa by adjusting exp, then convert to int
# 3.123E0 = 3123E-3, and 3.123E-2 => 3123E-5
{
}
# we can only have trailing zeros on the mantissa of $$mfv eq ''
{
if ($zeros != 0)
{
}
}
# for something like 0Ey, set y to 1, and -0 => +0
}
# if downgrade, inf, NaN or integers go down
{
{
}
}
}
sub copy
{
my ($c,$x);
if (@_ > 1)
{
# if two arguments, the first one is the class to "swallow" subclasses
($c,$x) = @_;
}
else
{
$x = shift;
$c = ref($x);
}
return unless ref($x); # only for objects
$self;
}
sub _bnan
{
# used by parent class bone() to initialize number to NaN
my $self = shift;
if ($_trap_nan)
{
require Carp;
Carp::croak ("Tried to set $self to NaN in $class\::_bnan()");
}
}
sub _binf
{
# used by parent class bone() to initialize number to +-inf
my $self = shift;
if ($_trap_inf)
{
require Carp;
Carp::croak ("Tried to set $self to +-inf in $class\::_binf()");
}
}
sub _bone
{
# used by parent class bone() to initialize number to 1
my $self = shift;
}
sub _bzero
{
# used by parent class bone() to initialize number to 0
my $self = shift;
}
sub isa
{
}
sub config
{
# return (later set?) configuration data as hash ref
my $class = shift || 'Math::BigFloat';
# now we need only to override the ones that are different from our parent
$cfg;
}
##############################################################################
# string conversation
sub bstr
{
# (ref to BFLOAT or num_str ) return num_str
# Convert number from internal format to (non-scientific) string format.
# internal format is always normalized (no leading zeros, "-0" => "+0")
if ($x->{sign} !~ /^[+-]$/)
{
return 'inf'; # +inf
}
# $x is zero?
if ($not_zero)
{
$e = -$e if $x->{_es} eq '-';
if ($e < 0)
{
$dot = '';
# if _e is bigger than a scalar, the following will blow your memory
if ($e <= -$len)
{
my $r = abs($e) - $len;
}
else
{
}
}
elsif ($e > 0)
{
# expand with zeros
}
} # if not zero
# if set accuracy or precision, pad with zeros on the right side
{
# 123400 => 6, 0.1234 => 4, 0.001234 => 4
}
{
# 123400 => 6, 0.1234 => 4, 0.001234 => 6
}
$es;
}
sub bsstr
{
# (ref to BFLOAT or num_str ) return num_str
# Convert number from internal format to scientific string format.
# internal format is always normalized (no leading zeros, "-0E0" => "+0E0")
if ($x->{sign} !~ /^[+-]$/)
{
return 'inf'; # +inf
}
}
sub numify
{
# Make a number from a BigFloat object
# simple return a string and let Perl's atoi()/atof() handle the rest
$x->bsstr();
}
##############################################################################
# public stuff (usually prefixed with "b")
# tels 2001-08-04
# XXX TODO this must be overwritten and return NaN for non-integer values
# band(), bior(), bxor(), too
#sub bnot
# {
# $class->SUPER::bnot($class,@_);
# }
sub bcmp
{
# Compares 2 values. Returns one of undef, <0, =0, >0. (suitable for sort)
# set up parameters
my ($self,$x,$y) = (ref($_[0]),@_);
# objectify is costly, so avoid it
if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1])))
{
}
{
# handle +-inf and NaN
return +1;
}
# check sign for speed first
# shortcut
# adjust so that exponents are equal
# the numify somewhat limits our length, but makes it much faster
return $l <=> 0 if $l != 0;
# lengths (corrected by exponent) are equal
# so make mantissa equal length by padding with zero (shift left)
if ($diff > 0)
{
}
elsif ($diff < 0)
{
}
$rc <=> 0;
}
sub bacmp
{
# Compares 2 values, ignoring their signs.
# Returns one of undef, <0, =0, >0. (suitable for sort)
# set up parameters
my ($self,$x,$y) = (ref($_[0]),@_);
# objectify is costly, so avoid it
if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1])))
{
}
# handle +-inf and NaN's
{
return -1;
}
# shortcut
# adjust so that exponents are equal
# the numify somewhat limits our length, but makes it much faster
return $l <=> 0 if $l != 0;
# lengths (corrected by exponent) are equal
# so make mantissa equal-length by padding with zero (shift left)
if ($diff > 0)
{
}
elsif ($diff < 0)
{
}
}
sub badd
{
# add second arg (BFLOAT or string) to first (BFLOAT) (modifies first)
# return result as BFLOAT
# set up parameters
my ($self,$x,$y,$a,$p,$r) = (ref($_[0]),@_);
# objectify is costly, so avoid it
if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1])))
{
}
# inf and NaN handling
{
# NaN first
# inf handling
{
# +inf++inf or -inf+-inf => same, rest is NaN
return $x->bnan();
}
# +-inf + something => +inf; something +-inf => +-inf
return $x;
}
# speed: no add for 0+y or x+0
if ($x->is_zero()) # 0+y
{
# make copy, clobbering up x (modify in place!)
return $x->round($a,$p,$r,$y);
}
# take lower of the two e's and adapt m1 to it to match m2
my $e = $y->{_e};
my $es;
{
}
{
}
# else: both e are the same, so just leave them
{
# add
}
else
{
}
# delete trailing zeros, then round
}
sub bsub
{
# (BigFloat or num_str, BigFloat or num_str) return BigFloat
# subtract second arg from first, modify first
# set up parameters
my ($self,$x,$y,$a,$p,$r) = (ref($_[0]),@_);
# objectify is costly, so avoid it
if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1])))
{
}
if ($y->is_zero()) # still round for not adding zero
{
return $x->round($a,$p,$r);
}
# $x - $y = -$x + $y
$y->{sign} =~ tr/+-/-+/; # does nothing for NaN
$x->badd($y,$a,$p,$r); # badd does not leave internal zeros
$y->{sign} =~ tr/+-/-+/; # refix $y (does nothing for NaN)
$x; # already rounded by badd()
}
sub binc
{
# increment arg by one
if ($x->{_es} eq '-')
{
}
{
# 1e2 => 100, so after the shift below _m has a '0' as last digit
$x->{_es} = '+';
# we know that the last digit of $x will be '1' or '9', depending on the
# sign
}
# now $x->{_e} == 0
if ($x->{sign} eq '+')
{
}
elsif ($x->{sign} eq '-')
{
}
# inf, nan handling etc
}
sub bdec
{
# decrement arg by one
if ($x->{_es} eq '-')
{
}
{
$x->{_es} = '+';
}
# now $x->{_e} == 0
# <= 0
{
}
# > 0
elsif ($x->{sign} eq '+')
{
}
# inf, nan handling etc
}
sub DEBUG () { 0; }
sub blog
{
# $base > 0, $base != 1; if $base == undef default to $base == e
# $x >= 0
# we need to limit the accuracy to protect against overflow
my $fallback = 0;
($x,@params) = $x->_find_round_parameters($a,$p,$r);
# also takes care of the "error in _find_round_parameters?" case
# no rounding at all, so must use fallback
if (scalar @params == 0)
{
# simulate old behaviour
}
else
{
# the 4 below is empirical, and there might be cases where it is not
# enough...
}
# base not defined => base == Euler's constant e
if (defined $base)
{
# make object, since we don't feed it through objectify() to still get the
# case of $base == undef
# $base > 0; $base != 1
# if $x == $base, we know the result must be 1.0
}
# when user set globals, they would interfere with our calculation, so
# disable them and later re-enable them
no strict 'refs';
# we also need to disable any set A or P on $x (_find_round_parameters took
# them already into account), since these would interfere, too
# need to disable $upgrade in BigInt, to avoid deep recursion
# upgrade $x if $x is not a BigFloat (handle BigInt input)
if (!$x->isa('Math::BigFloat'))
{
$self = ref($x);
}
my $done = 0;
# If the base is defined and an integer, try to calculate integer result
# first. This is very fast, and in case the real result was found, we can
# stop right here.
{
# if ($exact)
{
# found result, return it
$x->{_es} = '+';
$x->bnorm();
$done = 1;
}
}
if ($done == 0)
{
# first calculate the log to base e (using reduction by 10 (and probably 2))
# and if a different base was requested, convert it
if (defined $base)
{
# not ln, but some other base (don't modify $base)
}
}
# shortcut to not run through _find_round_parameters again
if (defined $params[0])
{
}
else
{
}
if ($fallback)
{
# clear a/p after round, since user did not request it
}
# restore globals
$x;
}
sub _log
{
# internal log function to calculate ln() based on Taylor series.
# Modifies $x in place.
# in case of $x == 1, result is 0
# u = x-1, v = x+1
# _ _
# Taylor: | u 1 u^3 1 u^5 |
# ln (x) = 2 | --- + - * --- + - * --- + ... | x > 0
# |_ v 3 v^3 5 v^5 _|
# This takes much more steps to calculate the result and is thus not used
# u = x-1
# _ _
# Taylor: | u 1 u^2 1 u^3 |
# ln (x) = 2 | --- + - * --- + - * --- + ... | x > 1/2
# |_ x 2 x^2 3 x^3 _|
$u *= $u; $v *= $v; # u^2, v^2
while (3 < 5)
{
# we calculate the next term, and add it to the last
# when the next term is below our limit, it won't affect the outcome
# anymore, so we stop
# a time hog if the input has many digits, since over and below will
# accumulate more and more digits, and the result will also have many
# digits, but in the end it is rounded to $scale digits anyway. So if we
# round $over and $below first, we save a lot of time for the division
# (not with log(1.2345), but try log (123**123) to see what I mean. This
# can introduce a rounding error if the division result would be f.i.
# 0.1234500000001 and we round it to 5 digits it would become 0.12346, but
# if we truncated $over and $below we might get 0.12345. Does this matter
# for the end result? So we give $over and $below 4 more digits to be
# on the safe side (unscientific error handling as usual... :+D
$scale);
## old version:
## $next = $over->copy()->bdiv($below->copy()->bmul($factor),$scale);
# calculate things for the next term
if (DEBUG)
{
}
}
$x->bmul($f); # $x *= 2
print "took $steps steps\n" if DEBUG;
}
sub _log_10
{
# Internal log function based on reducing input to the range of 0.1 .. 9.99
# and then "correcting" the result to the proper one. Modifies $x in place.
# taking blog() from numbers greater than 10 takes a *very long* time, so we
# break the computation down into parts based on the observation that:
# blog(x*y) = blog(x) + blog(y)
# We set $y here to multiples of 10 so that $x is below 1 (the smaller $x is
# the faster it get's, especially because 2*$x takes about 10 times as long,
# so by dividing $x by 10 we make it at least factor 100 faster...)
# The same observation is valid for numbers smaller than 0.1 (e.g. computing
# log(1) is fastest, and the farther away we get from 1, the longer it takes)
# so we also 'break' this down by multiplying $x with 10 and subtract the
# log(10) afterwards to get the correct result.
# calculate nr of digits before dot
# more than one digit (e.g. at least 10), but *not* exactly 10 to avoid
# infinite recursion
# disable the shortcut for 10, since we need log(10) and this would recurse
# infinitely deep
{
# we can use the cached value in these cases
{
}
}
else
{
# disable the shortcut for 2, since we maybe have it cached
{
# we can use the cached value in these cases
{
}
}
}
# if $x = 0.1, we know the result must be 0-log(10)
{
# we can use the cached value in these cases
{
}
}
# default: these correction factors are undef and thus not used
my $l_10; # value of ln(10) to A of $scale
my $l_2; # value of ln(2) to A of $scale
# $x == 2 => 1, $x == 13 => 2, $x == 0.1 => 0, $x == 0.01 => -1
# so don't do this shortcut for 1 or 0
{
# convert our cached value to an object if not already (avoid doing this
# at import() time, since not everybody needs this)
#print "x = $x, dbd = $dbd, calc = $calc\n";
# got more than one digit before the dot, or more than one zero after the
# dot, so do:
# log(123) == log(1.23) + log(10) * 2
# log(0.0123) == log(1.23) - log(10) * 2
{
# use cached value
}
else
{
# else: slower, compute it (but don't cache it, because it could be big)
# also disable downgrade for this code path
}
my $dbd_sign = '+';
if ($dbd < 0)
{
$dbd_sign = '-';
}
}
# Now: 0.1 <= $x < 10 (and possible correction in l_10)
### Since $x in the range 0.5 .. 1.5 is MUCH faster, we do a repeated div
### or mul by 2 (maximum times 3, since x < 10 and x > 0.1)
{
}
{
}
# $twos > 0 => did mul 2, < 0 => did div 2 (never both)
# calculate correction factor based on ln(2)
if ($twos != 0)
{
{
# use cached value
}
else
{
# else: slower, compute it (but don't cache it, because it could be big)
# also disable downgrade for this code path
}
}
# all done, $x contains now the result
}
sub blcm
{
# (BFLOAT or num_str, BFLOAT or num_str) return BFLOAT
# does not modify arguments, but returns new object
# Lowest Common Multiplicator
$x;
}
sub bgcd
{
# (BFLOAT or num_str, BFLOAT or num_str) return BINT
# does not modify arguments, but returns new object
# GCD -- Euclids algorithm Knuth Vol 2 pg 296
$x;
}
##############################################################################
sub _e_add
{
# Internal helper sub to take two positive integers and their signs and
# then add them. Input ($CALC,$CALC,('+'|'-'),('+'|'-')),
# output ($CALC,('+'|'-'))
# if the signs are equal we can add them (-5 + -3 => -(5 + 3) => -8)
{
# the sign follows $xs
return ($x, $xs);
}
if ($a > 0)
{
}
elsif ($a == 0)
{
$xs = '+';
}
else # a < 0
{
}
($x,$xs);
}
sub _e_sub
{
# Internal helper sub to take two positive integers and their signs and
# then subtract them. Input ($CALC,$CALC,('+'|'-'),('+'|'-')),
# output ($CALC,('+'|'-'))
# flip sign
$ys =~ tr/+-/-+/;
}
###############################################################################
# is_foo methods (is_negative, is_positive are inherited from BigInt)
sub is_int
{
# return true if arg (BFLOAT or num_str) is an integer
0;
}
sub is_zero
{
# return true if arg (BFLOAT or num_str) is zero
0;
}
sub is_one
{
# return true if arg (BFLOAT or num_str) is +1 or -1 if signis given
return 1
0;
}
sub is_odd
{
# return true if arg (BFLOAT or num_str) is odd or false if even
0;
}
sub is_even
{
# return true if arg (BINT or num_str) is even or false if odd
0;
}
sub bmul
{
# multiply two numbers -- stolen from Knuth Vol 2 pg 233
# (BINT or num_str, BINT or num_str) return BINT
# set up parameters
my ($self,$x,$y,$a,$p,$r) = (ref($_[0]),@_);
# objectify is costly, so avoid it
if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1])))
{
}
# inf handling
{
# result will always be +-inf:
# +inf * +/+inf => +inf, -inf * -/-inf => +inf
# +inf * -/-inf => -inf, -inf * +/+inf => -inf
return $x->binf('-');
}
# handle result = 0
# aEb * cEd = (a*c)E(b+d)
# adjust sign:
}
sub bdiv
{
# (dividend: BFLOAT or num_str, divisor: BFLOAT or num_str) return
# (BFLOAT,BFLOAT) (quo,rem) or BFLOAT (only rem)
# set up parameters
my ($self,$x,$y,$a,$p,$r) = (ref($_[0]),@_);
# objectify is costly, so avoid it
if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1])))
{
}
# x== 0 # also: or y == 1 or y == -1
# upgrade ?
# we need to limit the accuracy to protect against overflow
my $fallback = 0;
($x,@params) = $x->_find_round_parameters($a,$p,$r,$y);
return $x if $x->is_nan(); # error in _find_round_parameters?
# no rounding at all, so must use fallback
if (scalar @params == 0)
{
# simulate old behaviour
}
else
{
# the 4 below is empirical, and there might be cases where it is not
# enough...
}
# make copy of $x in case of list context for later reminder calculation
my $rem;
if (wantarray && !$y->is_one())
{
}
# check for / +-1 ( +/- 1E0)
if (!$y->is_one())
{
# promote BigInts and it's subclasses (except when already a BigFloat)
# calculate the result to $scale digits and then round it
# a * 10 ** b / c * 10 ** d => a/c * 10 ** (b-d)
# correct for 10**scale
$x->bnorm(); # remove trailing 0's
}
# shortcut to not run through _find_round_parameters again
if (defined $params[0])
{
delete $x->{_a}; # clear before round
}
else
{
delete $x->{_p}; # clear before round
}
if ($fallback)
{
# clear a/p after round, since user did not request it
}
if (wantarray)
{
if (!$y->is_one())
{
}
else
{
}
if ($fallback)
{
# clear a/p after round, since user did not request it
}
return ($x,$rem);
}
$x;
}
sub bmod
{
# (dividend: BFLOAT or num_str, divisor: BFLOAT or num_str) return reminder
# set up parameters
my ($self,$x,$y,$a,$p,$r) = (ref($_[0]),@_);
# objectify is costly, so avoid it
if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1])))
{
}
# handle NaN, inf, -inf
{
return $x->round($a,$p,$r,$y);
}
if ($y->is_zero())
{
return $x;
}
# only $y of the operands negative?
# 2e1 => 20
# if $y has digits after dot
{
# 123 % 2.5 => 1230 % 25 => 5 => 0.5
}
# $ym is now mantissa of $y based on exponent 0
{
# 123.4 % 20 => 1234 % 200
}
# 123e1 % 20 => 1230 % 20
{
}
$x->{_es} = '+';
# now mantissas are equalized, exponent of $x is adjusted, so calc result
$x->bnorm();
{
my $r = $y - $x;
$x->bnorm();
}
$x->round($a,$p,$r,$y); # round and return
}
sub broot
{
# calculate $y'th root of $x
# set up parameters
my ($self,$x,$y,$a,$p,$r) = (ref($_[0]),@_);
# objectify is costly, so avoid it
if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1])))
{
}
# NaN handling: $x ** 1/0, x or y NaN, or y inf/-inf or y == 0
$y->{sign} !~ /^\+$/;
# we need to limit the accuracy to protect against overflow
my $fallback = 0;
($x,@params) = $x->_find_round_parameters($a,$p,$r);
return $x if $x->is_nan(); # error in _find_round_parameters?
# no rounding at all, so must use fallback
if (scalar @params == 0)
{
# simulate old behaviour
}
else
{
# the 4 below is empirical, and there might be cases where it is not
# enough...
}
# when user set globals, they would interfere with our calculation, so
# disable them and later re-enable them
no strict 'refs';
# we also need to disable any set A or P on $x (_find_round_parameters took
# them already into account), since these would interfere, too
# need to disable $upgrade in BigInt, to avoid deep recursion
# remember sign and make $x positive, since -4 ** (1/2) => -2
my $is_two = 0;
if ($y->isa('Math::BigFloat'))
{
}
else
{
$is_two = ($y == 2);
}
# normal square root if $y == 2:
if ($is_two)
{
}
elsif ($y->is_one('-'))
{
# $x ** -1 => 1/$x
# copy private parts over
}
else
{
# calculate the broot() as integer result first, and if it fits, return
# it rightaway (but only if $x and $y are integer):
{
# if ($exact)
{
# found result, return it
$x->{_es} = '+';
$x->bnorm();
$done = 1;
}
}
if ($done == 0)
{
}
}
# shortcut to not run through _find_round_parameters again
if (defined $params[0])
{
}
else
{
}
if ($fallback)
{
# clear a/p after round, since user did not request it
}
# restore globals
$x;
}
sub bsqrt
{
# calculate square root
# we need to limit the accuracy to protect against overflow
my $fallback = 0;
($x,@params) = $x->_find_round_parameters($a,$p,$r);
return $x if $x->is_nan(); # error in _find_round_parameters?
# no rounding at all, so must use fallback
if (scalar @params == 0)
{
# simulate old behaviour
}
else
{
# the 4 below is empirical, and there might be cases where it is not
# enough...
}
# when user set globals, they would interfere with our calculation, so
# disable them and later re-enable them
no strict 'refs';
# we also need to disable any set A or P on $x (_find_round_parameters took
# them already into account), since these would interfere, too
# need to disable $upgrade in BigInt, to avoid deep recursion
# digits after the dot
{
# exact result, copy result over to keep $x
$x->bnorm();
# shortcut to not run through _find_round_parameters again
if (defined $params[0])
{
}
else
{
}
if ($fallback)
{
# clear a/p after round, since user did not request it
}
# re-enable A and P, upgrade is taken care of by "local"
return $x;
}
# sqrt(2) = 1.4 because sqrt(2*100) = 1.4*10; so we can increase the accuracy
# of the result by multipyling the input by 100 and then divide the integer
# result of sqrt(input) by 10. Rounding afterwards returns the real result.
# The following steps will transform 123.456 (in $x) into 123456 (in $y1)
# Now calculate how many digits the result of sqrt(y1) would have
# But we need at least $scale digits, so calculate how many are missing
# That should never happen (we take care of integer guesses above)
# $shift = 0 if $shift < 0;
# Multiply in steps of 100, by shifting left two times the "missing" digits
# We now make sure that $y1 has the same odd or even number of digits than
# $x had. So when _e of $x is odd, we must shift $y1 by one digit left,
# because we always must multiply by steps of 100 (sqrt(100) is 10) and not
# steps of 10. The length of $x does not count, since an even or odd number
# of digits before the dot is not changed by adding an even number of digits
# after the dot (the result is still odd or even digits long).
# now take the square root and truncate to integer
# By "shifting" $y1 right (by creating a negative _e) we calculate the final
# result, which is than later rounded to the desired scale.
# calculate how many zeros $x had after the '.' (or before it, depending
# on sign of $dat, the result should have half as many:
if ($dat > 0)
{
# no zeros after the dot (e.g. 1.23, 0.49 etc)
# preserve half as many digits before the dot than the input had
# (but round this "up")
}
else
{
}
if ($dat < 0)
{
$x->{_es} = '-';
}
else
{
$x->{_es} = '+';
}
$x->bnorm();
# shortcut to not run through _find_round_parameters again
if (defined $params[0])
{
}
else
{
}
if ($fallback)
{
# clear a/p after round, since user did not request it
}
# restore globals
$x;
}
sub bfac
{
# (BFLOAT or num_str, BFLOAT or num_str) return BFLOAT
# compute factorial number, modifies first argument
# set up parameters
my ($self,$x,@r) = (ref($_[0]),@_);
# objectify is costly, so avoid it
return $x->bnan()
# use BigInt's bfac() for faster calc
{
$x->{_es} = '+';
}
}
sub _pow
{
# Calculate a power where $y is a non-integer, like 2 ** 0.5
my ($x,$y,$a,$p,$r) = @_;
my $self = ref($x);
# if $y == 0.5, it is sqrt($x)
# Using:
# a ** x == e ** (x * ln a)
# u = y * ln x
# _ _
# Taylor: | u u^2 u^3 |
# x ** y = 1 + | --- + --- + ----- + ... |
# |_ 1 1*2 1*2*3 _|
# we need to limit the accuracy to protect against overflow
my $fallback = 0;
($x,@params) = $x->_find_round_parameters($a,$p,$r);
return $x if $x->is_nan(); # error in _find_round_parameters?
# no rounding at all, so must use fallback
if (scalar @params == 0)
{
# simulate old behaviour
}
else
{
# the 4 below is empirical, and there might be cases where it is not
# enough...
}
# when user set globals, they would interfere with our calculation, so
# disable them and later re-enable them
no strict 'refs';
# we also need to disable any set A or P on $x (_find_round_parameters took
# them already into account), since these would interfere, too
# need to disable $upgrade in BigInt, to avoid deep recursion
$x->bone(); # first term: 1
#my $steps = 0;
while (3 < 5)
{
# we calculate the next term, and add it to the last
# when the next term is below our limit, it won't affect the outcome
# anymore, so we stop
# calculate things for the next term
last if $x->{sign} !~ /^[-+]$/;
#$steps++;
}
# shortcut to not run through _find_round_parameters again
if (defined $params[0])
{
}
else
{
}
if ($fallback)
{
# clear a/p after round, since user did not request it
}
# restore globals
$x;
}
sub bpow
{
# (BFLOAT or num_str, BFLOAT or num_str) return BFLOAT
# compute power of two numbers, second arg is used as integer
# modifies first argument
# set up parameters
my ($self,$x,$y,$a,$p,$r) = (ref($_[0]),@_);
# objectify is costly, so avoid it
if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1])))
{
}
# if ($x == -1)
{
}
if ($x->is_zero())
{
# 0 ** -y => 1 / (0 ** y) => 1 / 0! (1 / 0 => +inf)
return $x->binf();
}
my $new_sign = '+';
# calculate $x->{_m} ** $y and $x->{_e} * $y separately (faster)
$x->bnorm();
if ($y->{sign} eq '-')
{
# modify $x in place!
return $x->bdiv($z,$a,$p,$r); # round in one go (might ignore y's A!)
}
$x->round($a,$p,$r,$y);
}
###############################################################################
# rounding functions
sub bfround
{
# precision: round to the $Nth digit left (+$n) or right (-$n) from the '.'
# $n == 0 means round to integer
# expects and returns normalized numbers!
return $x if $x->modify('bfround');
return $x if !defined $scale; # no-op
# never round a 0, +-inf, NaN
if ($x->is_zero())
{
return $x;
}
return $x if $x->{sign} !~ /^[+-]$/;
# don't round if x already has lower precision
delete $x->{_a}; # and clear A
if ($scale < 0)
{
# round right from the '.'
# the following poses a restriction on _e, but if _e is bigger than a
# scalar, you got other problems (memory etc) anyway
# p rint "scale $scale dad $dad zad $zad len $len\n";
# number bsstr len zad dad
# 0.123 123e-3 3 0 3
# 0.0123 123e-4 3 1 4
# 0.001 1e-3 1 2 3
# 1.23 123e-2 3 0 2
# 1.2345 12345e-4 5 0 4
# round to zero if rounding inside the $zad, but not for last zero like:
# 0.0065, scale -2, round last '0' with following '65' (scale == zad case)
{
}
else
{
# adjust round-point to be inside mantissa
if ($zad != 0)
{
}
else
{
}
}
}
else
{
# round left from the '.'
# 123 => 100 means length(123) = 3 - $scale (2) => 1
# digits before dot
# should be the same, so treat it as this
# shortcut if already integer
# maximum digits before dot
++$dbd;
{
# not enough digits before dot, so round to zero
return $x->bzero;
}
{
# maximum
}
else
{
}
}
# pass sign to bround for rounding modes '+inf' and '-inf'
$x->bnorm();
}
sub bround
{
# accuracy: preserve $N digits, and overwrite the rest with 0's
if (($_[0] || 0) < 0)
{
}
return $x if !defined $scale; # no-op
return $x if $x->modify('bround');
# scale is now either $x->{_a}, $accuracy, or the user parameter
# test whether $x already has lower accuracy, do nothing in this case
# but do round if the accuracy is the same, since a math operation might
# want to round a number with A=5 to 5 digits afterwards again
# scale < 0 makes no sense
# never round a +-inf, NaN
# 1: $scale == 0 => keep all digits
# 2: never round a 0
# 3: if we should keep more digits than the mantissa has, do nothing
{
return $x;
}
# pass sign to bround for '+inf' and '-inf' rounding modes
delete $x->{_p}; # and clear P
$x->bnorm(); # del trailing zeros gen. by bround()
}
sub bfloor
{
# return integer less or equal then $x
return $x if $x->modify('bfloor');
return $x if $x->{sign} !~ /^[+-]$/; # nan, +inf, -inf
# if $x has digits after dot
if ($x->{_es} eq '-')
{
}
$x->round($a,$p,$r);
}
sub bceil
{
# return integer greater or equal then $x
return $x if $x->modify('bceil');
return $x if $x->{sign} !~ /^[+-]$/; # nan, +inf, -inf
# if $x has digits after dot
if ($x->{_es} eq '-')
{
}
$x->round($a,$p,$r);
}
sub brsft
{
# shift right by $y (divide by power of $n)
# set up parameters
my ($self,$x,$y,$n,$a,$p,$r) = (ref($_[0]),@_);
# objectify is costly, so avoid it
if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1])))
{
}
return $x if $x->modify('brsft');
return $x if $x->{sign} !~ /^[+-]$/; # nan, +inf, -inf
$n = 2 if !defined $n; $n = $self->new($n);
}
sub blsft
{
# shift left by $y (multiply by power of $n)
# set up parameters
my ($self,$x,$y,$n,$a,$p,$r) = (ref($_[0]),@_);
# objectify is costly, so avoid it
if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1])))
{
}
return $x if $x->modify('blsft');
return $x if $x->{sign} !~ /^[+-]$/; # nan, +inf, -inf
$n = 2 if !defined $n; $n = $self->new($n);
}
###############################################################################
sub DESTROY
{
# going through AUTOLOAD for every DESTROY is costly, avoid it by empty sub
}
sub AUTOLOAD
{
# make fxxx and bxxx both work by selectively mapping fxxx() to MBF::bxxx()
# or falling back to MBI::bxxx()
$name =~ s/(.*):://; # split package
my $c = $1 || $class;
no strict 'refs';
$c->import() if $IMPORT == 0;
if (!method_alias($name))
{
if (!defined $name)
{
# delayed load of Carp and avoid recursion
require Carp;
Carp::croak ("$c: Can't call a method without name");
}
if (!method_hand_up($name))
{
# delayed load of Carp and avoid recursion
require Carp;
Carp::croak ("Can't call $c\-\>$name, not a valid method");
}
# try one level up, but subst. bxxx() for fxxx() since MBI only got bxxx()
$name =~ s/^f/b/;
return &{"Math::BigInt"."::$name"}(@_);
}
$c .= "::$name";
*{$c} = \&{$bname};
&{$c}; # uses @_
}
sub exponent
{
# return a copy of the exponent
if ($x->{sign} !~ /^[+-]$/)
{
my $s = $x->{sign}; $s =~ s/^[+-]//;
}
}
sub mantissa
{
# return a copy of the mantissa
if ($x->{sign} !~ /^[+-]$/)
{
my $s = $x->{sign}; $s =~ s/^[+]//;
}
$m;
}
sub parts
{
# return a copy of both the exponent and the mantissa
if ($x->{sign} !~ /^[+-]$/)
{
}
}
##############################################################################
# private stuff (internal use only)
sub import
{
my $self = shift;
my $l = scalar @_;
my $lib = ''; my @a;
$IMPORT=1;
for ( my $i = 0; $i < $l ; $i++)
{
if ( $_[$i] eq ':constant' )
{
# This causes overlord er load to step in. 'binary' and 'integer'
# are handled by BigInt.
}
elsif ($_[$i] eq 'upgrade')
{
# this causes upgrading
$i++;
}
elsif ($_[$i] eq 'downgrade')
{
# this causes downgrading
$i++;
}
elsif ($_[$i] eq 'lib')
{
# alternative library
$i++;
}
elsif ($_[$i] eq 'with')
{
# alternative class for our private parts()
# XXX: no longer supported
# $MBI = $_[$i+1] || 'Math::BigInt';
$i++;
}
else
{
push @a, $_[$i];
}
}
# let use Math::BigInt lib => 'GMP'; use Math::BigFloat; still work
{
# MBI already loaded
}
else
{
# MBI not loaded, or with ne "Math::BigInt::Calc"
$lib =~ s/^,//; # don't leave empty
# replacement library can handle lib statement, but also could ignore it
if ($] < 5.006)
{
# Perl < 5.6.0 dies with "out of memory!" when eval() and ':constant' is
# used in the same script, or eval inside import().
}
else
{
my $rc = "use Math::BigInt lib => '$lib', 'objectify';";
eval $rc;
}
}
if ($@)
{
}
# any non :constant stuff is handled by our parent, Exporter
# even if @_ is empty, to give it a chance
}
sub bnorm
{
# adjust m and e so that m is smallest possible
# round number according to accuracy and precision settings
return $x if $x->{sign} !~ /^[+-]$/; # inf, nan etc
if ($zeros != 0)
{
if ($x->{_es} eq '-')
{
{
}
else
{
$x->{_es} = '+';
}
}
else
{
}
}
else
{
# $x can only be 0Ey if there are no trailing zeros ('0' has 0 trailing
# zeros). So, for something like 0Ey, set y to 1, and -0 => +0
}
$x; # MBI bnorm is no-op, so dont call it
}
##############################################################################
sub as_hex
{
# return number as hexadecimal string (only for integers defined)
return '0x0' if $x->is_zero();
{
}
$z->as_hex();
}
sub as_bin
{
# return number as binary digit string (only for integers defined)
return '0b0' if $x->is_zero();
{
}
$z->as_bin();
}
sub as_number
{
# return copy as a bigint representation of this BigFloat number
{
}
{
}
$z;
}
sub length
{
my $x = shift;
my $class = ref($x) || $x;
$x = $class->new(shift) unless ref($x);
if (wantarray())
{
my $t = 0;
return ($len, $t);
}
$len;
}
1;
=head1 NAME
Math::BigFloat - Arbitrary size floating point math package
=head1 SYNOPSIS
use Math::BigFloat;
# Number creation
$x = Math::BigFloat->new($str); # defaults to 0
$nan = Math::BigFloat->bnan(); # create a NotANumber
$zero = Math::BigFloat->bzero(); # create a +0
$inf = Math::BigFloat->binf(); # create a +inf
$inf = Math::BigFloat->binf('-'); # create a -inf
$one = Math::BigFloat->bone(); # create a +1
$one = Math::BigFloat->bone('-'); # create a -1
# Testing
$x->is_zero(); # true if arg is +0
$x->is_nan(); # true if arg is NaN
$x->is_one(); # true if arg is +1
$x->is_one('-'); # true if arg is -1
$x->is_odd(); # true if odd, false for even
$x->is_even(); # true if even, false for odd
$x->is_pos(); # true if >= 0
$x->is_neg(); # true if < 0
$x->is_inf(sign); # true if +inf, or -inf (default is '+')
$x->bcmp($y); # compare numbers (undef,<0,=0,>0)
$x->bacmp($y); # compare absolutely (undef,<0,=0,>0)
$x->sign(); # return the sign, either +,- or NaN
$x->digit($n); # return the nth digit, counting from right
$x->digit(-$n); # return the nth digit, counting from left
# The following all modify their first argument. If you want to preserve
# $x, use $z = $x->copy()->bXXX($y); See under L<CAVEATS> for why this is
# neccessary when mixing $a = $b assigments with non-overloaded math.
# set
$x->bzero(); # set $i to 0
$x->bnan(); # set $i to NaN
$x->bone(); # set $x to +1
$x->bone('-'); # set $x to -1
$x->binf(); # set $x to inf
$x->binf('-'); # set $x to -inf
$x->bneg(); # negation
$x->babs(); # absolute value
$x->bnorm(); # normalize (no-op)
$x->bnot(); # two's complement (bit wise not)
$x->binc(); # increment x by 1
$x->bdec(); # decrement x by 1
$x->badd($y); # addition (add $y to $x)
$x->bsub($y); # subtraction (subtract $y from $x)
$x->bmul($y); # multiplication (multiply $x by $y)
$x->bdiv($y); # divide, set $x to quotient
# return (quo,rem) or quo if scalar
$x->bmod($y); # modulus ($x % $y)
$x->bpow($y); # power of arguments ($x ** $y)
$x->blsft($y); # left shift
$x->brsft($y); # right shift
# return (quo,rem) or quo if scalar
$x->blog(); # logarithm of $x to base e (Euler's number)
$x->blog($base); # logarithm of $x to base $base (f.i. 2)
$x->band($y); # bit-wise and
$x->bior($y); # bit-wise inclusive or
$x->bxor($y); # bit-wise exclusive or
$x->bnot(); # bit-wise not (two's complement)
$x->bsqrt(); # calculate square-root
$x->broot($y); # $y'th root of $x (e.g. $y == 3 => cubic root)
$x->bfac(); # factorial of $x (1*2*3*4*..$x)
$x->bround($N); # accuracy: preserve $N digits
$x->bfround($N); # precision: round to the $Nth digit
$x->bfloor(); # return integer less or equal than $x
$x->bceil(); # return integer greater or equal than $x
# The following do not modify their arguments:
bgcd(@values); # greatest common divisor
blcm(@values); # lowest common multiplicator
$x->bstr(); # return string
$x->bsstr(); # return string in scientific notation
$x->as_int(); # return $x as BigInt
$x->exponent(); # return exponent as BigInt
$x->mantissa(); # return mantissa as BigInt
$x->parts(); # return (mantissa,exponent) as BigInt
$x->length(); # number of digits (w/o sign and '.')
($l,$f) = $x->length(); # number of digits, and length of fraction
$x->precision(); # return P of $x (or global, if P of $x undef)
$x->precision($n); # set P of $x to $n
$x->accuracy(); # return A of $x (or global, if A of $x undef)
$x->accuracy($n); # set A $x to $n
Math::BigFloat->precision(); # Precision
Math::BigFloat->accuracy(); # Accuracy
Math::BigFloat->round_mode(); # rounding mode
=head1 DESCRIPTION
All operators (inlcuding basic math operations) are overloaded if you
declare your big floating point numbers as
$i = new Math::BigFloat '12_3.456_789_123_456_789E-2';
Operations with overloaded operators preserve the arguments, which is
exactly what you expect.
=head2 Canonical notation
Input to these routines are either BigFloat objects, or strings of the
following four forms:
=over 2
=item *
C</^[+-]\d+$/>
=item *
C</^[+-]\d+\.\d*$/>
=item *
C</^[+-]\d+E[+-]?\d+$/>
=item *
C</^[+-]\d*\.\d+E[+-]?\d+$/>
=back
numbers are allowed to have an underscore between any two digits.
Empty strings as well as other illegal numbers results in 'NaN'.
bnorm() on a BigFloat object is now effectively a no-op, since the numbers
are always stored in normalized form. On a string, it creates a BigFloat
object.
=head2 Output
Output values are BigFloat objects (normalized), except for bstr() and bsstr().
The string output will always have leading and trailing zeros stripped and drop
a plus sign. C<bstr()> will give you always the form with a decimal point,
while C<bsstr()> (s for scientific) gives you the scientific notation.
Input bstr() bsstr()
'-0' '0' '0E1'
' -123 123 123' '-123123123' '-123123123E0'
'00.0123' '0.0123' '123E-4'
'123.45E-2' '1.2345' '12345E-4'
'10E+3' '10000' '1E4'
Some routines (C<is_odd()>, C<is_even()>, C<is_zero()>, C<is_one()>,
C<is_nan()>) return true or false, while others (C<bcmp()>, C<bacmp()>)
return either undef, <0, 0 or >0 and are suited for sort.
Actual math is done by using the class defined with C<with => Class;> (which
defaults to BigInts) to represent the mantissa and exponent.
The sign C</^[+-]$/> is stored separately. The string 'NaN' is used to
represent the result when input arguments are not numbers, as well as
the result of dividing by zero.
=head2 C<mantissa()>, C<exponent()> and C<parts()>
C<mantissa()> and C<exponent()> return the said parts of the BigFloat
as BigInts such that:
$m = $x->mantissa();
$e = $x->exponent();
$y = $m * ( 10 ** $e );
print "ok\n" if $x == $y;
C<< ($m,$e) = $x->parts(); >> is just a shortcut giving you both of them.
A zero is represented and returned as C<0E1>, B<not> C<0E0> (after Knuth).
Currently the mantissa is reduced as much as possible, favouring higher
exponents over lower ones (e.g. returning 1e7 instead of 10e6 or 10000000e0).
This might change in the future, so do not depend on it.
=head2 Accuracy vs. Precision
See also: L<Rounding|Rounding>.
Math::BigFloat supports both precision and accuracy. For a full documentation,
examples and tips on these topics please see the large section in
L<Math::BigInt>.
Since things like sqrt(2) or 1/3 must presented with a limited precision lest
a operation consumes all resources, each operation produces no more than
the requested number of digits.
Please refer to BigInt's documentation for the precedence rules of which
If there is no gloabl precision set, B<and> the operation inquestion was not
called with a requested precision or accuracy, B<and> the input $x has no
accuracy or precision set, then a fallback parameter will be used. For
historical reasons, it is called C<div_scale> and can be accessed via:
$d = Math::BigFloat->div_scale(); # query
Math::BigFloat->div_scale($n); # set to $n digits
The default value is 40 digits.
In case the result of one operation has more precision than specified,
it is rounded. The rounding mode taken is either the default mode, or the one
supplied to the operation after the I<scale>:
$x = Math::BigFloat->new(2);
Math::BigFloat->precision(5); # 5 digits max
$y = $x->copy()->bdiv(3); # will give 0.66666
$y = $x->copy()->bdiv(3,6); # will give 0.666666
$y = $x->copy()->bdiv(3,6,'odd'); # will give 0.666667
Math::BigFloat->round_mode('zero');
$y = $x->copy()->bdiv(3,6); # will give 0.666666
=head2 Rounding
=over 2
=item ffround ( +$scale )
Rounds to the $scale'th place left from the '.', counting from the dot.
The first digit is numbered 1.
=item ffround ( -$scale )
Rounds to the $scale'th place right from the '.', counting from the dot.
=item ffround ( 0 )
Rounds to an integer.
=item fround ( +$scale )
Preserves accuracy to $scale digits from the left (aka significant digits)
and pads the rest with zeros. If the number is between 1 and -1, the
significant digits count from the first non-zero after the '.'
=item fround ( -$scale ) and fround ( 0 )
These are effectively no-ops.
=back
All rounding functions take as a second parameter a rounding mode from one of
the following: 'even', 'odd', '+inf', '-inf', 'zero' or 'trunc'.
The default rounding mode is 'even'. By using
C<< Math::BigFloat->round_mode($round_mode); >> you can get and set the default
mode for subsequent rounding. The usage of C<$Math::BigFloat::$round_mode> is
no longer supported.
The second parameter to the round functions then overrides the default
temporarily.
The C<as_number()> function returns a BigInt from a Math::BigFloat. It uses
'trunc' as rounding mode to make it equivalent to:
$x = 2.5;
$y = int($x) + 2;
You can override this by passing the desired rounding mode as parameter to
C<as_number()>:
$x = Math::BigFloat->new(2.5);
$y = $x->as_number('odd'); # $y = 3
=head1 EXAMPLES
# not ready yet
=head1 Autocreating constants
After C<use Math::BigFloat ':constant'> all the floating point constants
in the given scope are converted to C<Math::BigFloat>. This conversion
happens at compile time.
In particular
perl -MMath::BigFloat=:constant -e 'print 2E-100,"\n"'
prints the value of C<2E-100>. Note that without conversion of
constants the expression 2E-100 will be calculated as normal floating point
number.
Please note that ':constant' does not affect integer constants, nor binary
nor hexadecimal constants. Use L<bignum> or L<Math::BigInt> to get this to
work.
=head2 Math library
Math with the numbers is done (by default) by a module called
Math::BigInt::Calc. This is equivalent to saying:
use Math::BigFloat lib => 'Calc';
You can change this by using:
use Math::BigFloat lib => 'BitVect';
The following would first try to find Math::BigInt::Foo, then
Math::BigInt::Bar, and when this also fails, revert to Math::BigInt::Calc:
use Math::BigFloat lib => 'Foo,Math::BigInt::Bar';
Calc.pm uses as internal format an array of elements of some decimal base
(usually 1e7, but this might be differen for some systems) with the least
significant digit first, while BitVect.pm uses a bit vector of base 2, most
significant bit first. Other modules might use even different means of
representing the numbers. See the respective module documentation for further
details.
Please note that Math::BigFloat does B<not> use the denoted library itself,
but it merely passes the lib argument to Math::BigInt. So, instead of the need
to do:
use Math::BigInt lib => 'GMP';
use Math::BigFloat;
you can roll it all into one line:
use Math::BigFloat lib => 'GMP';
It is also possible to just require Math::BigFloat:
require Math::BigFloat;
This will load the neccessary things (like BigInt) when they are needed, and
automatically.
Use the lib, Luke! And see L<Using Math::BigInt::Lite> for more details than
you ever wanted to know about loading a different library.
=head2 Using Math::BigInt::Lite
It is possible to use L<Math::BigInt::Lite> with Math::BigFloat:
# 1
use Math::BigFloat with => 'Math::BigInt::Lite';
There is no need to "use Math::BigInt" or "use Math::BigInt::Lite", but you
can combine these if you want. For instance, you may want to use
Math::BigInt objects in your main script, too.
# 2
use Math::BigInt;
use Math::BigFloat with => 'Math::BigInt::Lite';
Of course, you can combine this with the C<lib> parameter.
# 3
use Math::BigFloat with => 'Math::BigInt::Lite', lib => 'GMP,Pari';
There is no need for a "use Math::BigInt;" statement, even if you want to
use Math::BigInt's, since Math::BigFloat will needs Math::BigInt and thus
always loads it. But if you add it, add it B<before>:
# 4
use Math::BigInt;
use Math::BigFloat with => 'Math::BigInt::Lite', lib => 'GMP,Pari';
Notice that the module with the last C<lib> will "win" and thus
it's lib will be used if the lib is available:
# 5
use Math::BigInt lib => 'Bar,Baz';
use Math::BigFloat with => 'Math::BigInt::Lite', lib => 'Foo';
That would try to load Foo, Bar, Baz and Calc (in that order). Or in other
words, Math::BigFloat will try to retain previously loaded libs when you
don't specify it onem but if you specify one, it will try to load them.
Actually, the lib loading order would be "Bar,Baz,Calc", and then
"Foo,Bar,Baz,Calc", but independend of which lib exists, the result is the
same as trying the latter load alone, except for the fact that one of Bar or
Baz might be loaded needlessly in an intermidiate step (and thus hang around
actually loading one of them. Still, this type of usage is not recommended due
to these issues.
The old way (loading the lib only in BigInt) still works though:
# 6
use Math::BigInt lib => 'Bar,Baz';
use Math::BigFloat;
You can even load Math::BigInt afterwards:
# 7
use Math::BigFloat;
use Math::BigInt lib => 'Bar,Baz';
But this has the same problems like #5, it will first load Calc
(Math::BigFloat needs Math::BigInt and thus loads it) and then later Bar or
loads Calc unnecc., it is not recommended.
Since it also possible to just require Math::BigFloat, this poses the question
about what libary this will use:
require Math::BigFloat;
my $x = Math::BigFloat->new(123); $x += 123;
It will use Calc. Please note that the call to import() is still done, but
only when you use for the first time some Math::BigFloat math (it is triggered
via any constructor, so the first time you create a Math::BigFloat, the load
will happen in the background). This means:
require Math::BigFloat;
Math::BigFloat->import ( lib => 'Foo,Bar' );
would be the same as:
use Math::BigFloat lib => 'Foo, Bar';
But don't try to be clever to insert some operations in between:
require Math::BigFloat;
my $x = Math::BigFloat->bone() + 4; # load BigInt and Calc
Math::BigFloat->import( lib => 'Pari' ); # load Pari, too
$x = Math::BigFloat->bone()+4; # now use Pari
While this works, it loads Calc needlessly. But maybe you just wanted that?
B<Examples #3 is highly recommended> for daily usage.
=head1 BUGS
Please see the file BUGS in the CPAN distribution Math::BigInt for known bugs.
=head1 CAVEATS
=over 1
=item stringify, bstr()
Both stringify and bstr() now drop the leading '+'. The old code would return
'+1.23', the new returns '1.23'. See the documentation in L<Math::BigInt> for
reasoning and details.
=item bdiv
The following will probably not do what you expect:
print $c->bdiv(123.456),"\n";
It prints both quotient and reminder since print works in list context. Also,
bdiv() will modify $c, so be carefull. You probably want to use
print $c / 123.456,"\n";
print scalar $c->bdiv(123.456),"\n"; # or if you want to modify $c
instead.
=item Modifying and =
Beware of:
$x = Math::BigFloat->new(5);
$y = $x;
It will not do what you think, e.g. making a copy of $x. Instead it just makes
a second reference to the B<same> object and stores it in $y. Thus anything
that modifies $x will modify $y (except overloaded math operators), and vice
versa. See L<Math::BigInt> for details and how to avoid that.
=item bpow
C<bpow()> now modifies the first argument, unlike the old code which left
it alone and only returned the result. This is to be consistent with
C<badd()> etc. The first will modify $x, the second one won't:
print bpow($x,$i),"\n"; # modify $x
print $x->bpow($i),"\n"; # ditto
print $x ** $i,"\n"; # leave $x alone
=back
=head1 SEE ALSO
L<Math::BigInt>, L<Math::BigRat> and L<Math::Big> as well as
L<Math::BigInt::BitVect>, L<Math::BigInt::Pari> and L<Math::BigInt::GMP>.
The pragmas L<bignum>, L<bigint> and L<bigrat> might also be of interest
because they solve the autoupgrading/downgrading issue, at least partly.
The package at
more documentation including a full version history, testcases, empty
subclass files and benchmarks.
=head1 LICENSE
the same terms as Perl itself.
=head1 AUTHORS
Mark Biggar, overloaded interface by Ilya Zakharevich.
Completely rewritten by Tels http://bloodgate.com in 2001, 2002, and still
at it in 2003.
=cut