Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conversion in java

Tags:

java

My question is pertaining to conversion in java. I have an integer 1615021049. When in divide it by 1(which is also a float), the answer i get in float is 1.61502106E9, which when converted back to integer gives me 1615021056 which is not the original number. Kindly help. The same works properly, if i convert the variables m and b to double.

int a=1615021023;
float m=1;
float b=a/m;
int d= (int) b;
like image 595
user1947679 Avatar asked Dec 20 '22 11:12

user1947679


2 Answers

The problem is that float's mantissa has too few bits to represent 1615021049 exactly. The latter requires 31 bits, and the former only offers 23. Hence the loss of precision.

This isn't an issue with doubles because a double has 52 bits of mantissa, enough to represent 1615021049.

See Wikipedia.

like image 177
NPE Avatar answered Dec 23 '22 01:12

NPE


There are an infinity of real numbers. There are only 32 bits in a float. So obviously, not every real can be represented accurately as a float. And the float representation makes small numbers more accurate than large ones.

like image 23
JB Nizet Avatar answered Dec 23 '22 02:12

JB Nizet