| Author |
bigInteger to float or double
|
chop ficaro
Ranch Hand
Joined: May 02, 2010
Posts: 30
|
|
|
ive got a java.math.bigInteger in the DENOMINATOR of a function, and i need it to return a float. how do i do this while keeping as much accuracy as possible (the denominator could be as large as 10^80)
|
 |
Rob Spoor
Sheriff
Joined: Oct 27, 2005
Posts: 19216
|
|
|
As soon as you turn it into a float you've lost quite a bit of accuracy already. That's because float only has 32 bits in which to store both the integer and the decimal part. double is better but still limited. The only way to maintain your accuracy is to keep using BigInteger.
|
SCJP 1.4 - SCJP 6 - SCWCD 5
How To Ask Questions How To Answer Questions
|
 |
Mike Simmons
Ranch Hand
Joined: Mar 05, 2008
Posts: 2770
|
|
|
This is true. However if indeed you have to return a float (perhaps because you're implementing a method that returns a float, and can't edit the original interface) then the question was how to do this with as much accuracy as possible. Under these conditions I would simply use BigInteger's doubleValue() method, perform the division, and then cast the result to float. There may be other ways equally accurate, but there isn't really any way that's more accurate. You should get nearly the same result by converting to floatValue() and then dividing - but it's a little more accurate if you use the more precise value (a double) for as long as you can.
|
 |
 |
|
|
subject: bigInteger to float or double
|
|
|