commons-dev mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From "J.Pietschmann" <j3322...@yahoo.de>
Subject Math.pow usage was: Re: cvs commit: ...
Date Wed, 18 Jun 2003 17:37:42 GMT
> accum += Math.pow(values[i], 2.0);

I think Math.pow should not be used for small integer exponents,
in particular 2,3 and perhaps 5. You could do this in FORTRAN or
other languages with a built-in power operator, because the compiler
will optimize it, but languages without that usually rewrite
pos(x,y) as exp(y*log(x)). This is bad for precision, in particular
if x is very small, and somewhat bad for performance (taking time of
one multiplication and two divisions, typically costing 3 to 20 times
as much as a multiplication each).
I'm not sure how Java handles it, but the loss of precision may
be responsible for the unexpected negative values.

I'd recommend to replace pow(x,2) by x*x, pow(x,3) by x*x*x and
pow(x,4) by a=x*x, y=a*a. It doesn't matter much whether x is an
expression because the compiler will take care of it and eliminate
redundant computation, however code may be more redable if a
temporary variable is used. If x is an integer, an explicit cast
to double may be necessary to avoid integer overflow.

Math.pow should only be used if the exponent is larger, not an
integer, or not a constant.

J.Pietschmann



---------------------------------------------------------------------
To unsubscribe, e-mail: commons-dev-unsubscribe@jakarta.apache.org
For additional commands, e-mail: commons-dev-help@jakarta.apache.org


Mime
View raw message