Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

bigInteger to float or double

 
chop ficaro
Ranch Hand
Posts: 30
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 20511
54
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Mike Simmons
Ranch Hand
Posts: 3036
10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic