# commons-dev mailing list archives

##### Site index · List index
Message view
Top
From "Mark R. Diggory" <mdigg...@latte.harvard.edu>
Subject Re: [math] Math.pow usage was: Re: cvs commit: ...
Date Thu, 19 Jun 2003 04:54:37 GMT
```Phil Steitz wrote:
> --- "Mark R. Diggory" <mdiggory@latte.harvard.edu> wrote:
>
>>Thanks for entertaining my sometimes naive questioning,
>>
>>J.Pietschmann wrote:
>>>No. If you cast the base into a double there is not much risk of
>>>overflow: double x = n;  y=x*x; or y=((double)n)*((double)n);
>>>or even y=n*(double)n; (but avoid y=(double)n*n).
>>>Double mantissa has IIRC 52 bits, this should be good for integers
>>>up to 2^26=67108864 without loss of precision.

Is this correct, I've been reading (again, if I'm getting this
correctly) the doubles mantissa is capable of supporting 15 -17 decimal
places, 2^26 is only 8.

http://www.particle.kth.se/~lindsey/JavaCourse/Book/Tech/Chapter02/floatingPt.html

>>
>>Wow, thats a great clarification, I understand your defense now. It
>>would be best to cast n to double asap and always have * operating on
>>doubles, so doing things like consolidating the casting of n like this
>>
>>((double) (n*(n - 1)))
>
>
>>is a poor choice, if I understand correctly, its wiser to do at least
>>
>>((double) n) * (n - 1)
>
>
> For avoiding overflow maybe, but not for precision, since if n is a long,
> n*(n-1) will be computed exactly in the first case and then cast to a double.
>

Just to clarify, and if I understand correctly, we are only talking
about n in terms of "values.length". n is currently any integer >= 0.
The concern is that calculating n*n for any n > Integer.MAX_VALUE^(1/2)
and for calculating n*n*n for any n > Integer.MAX_VALUE^(1/3) there is
significant overflow that can easily be rectified through pre-casting to
doubles.

I think, that its only when the case that such a method begins to loose
precision above the threshold of the double's mantissa of IIRC 52 bits
which I think is ~1.0 x 10^17 significant digits, not quite as good as
~1.0 x 10^19 max for long integers, but the behavior is more stable for
larger doubles than for longs, resulting initially in loss of precision
for numbers > ~1.0 x 10^17 instead of a hard overflow.

From this I now draw that its often better to cast the int "n" to
double prior to any operations preformed on it.

-Mark

---------------------------------------------------------------------
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