Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why when I assign an int to a float is it not the same value?

Tags:

java

When I assign from an int to a float I thought float allows more precision, so would not lose or change the value assigned, but what I am seeing is something quite different. What is going on here?

for(int i = 63000000; i < 63005515; i++) { 
   int a = i;
   float f = 0; 
   f=a; 
   System.out.print(java.text.NumberFormat.getInstance().format(a) + " : " );
   System.out.println(java.text.NumberFormat.getInstance().format(f));
} 

some of the output :

...

63,005,504 : 63,005,504

63,005,505 : 63,005,504

63,005,506 : 63,005,504

63,005,507 : 63,005,508

63,005,508 : 63,005,508

Thanks!

like image 478
WizardsOfWor Avatar asked Dec 01 '22 16:12

WizardsOfWor


1 Answers

A float has the same number of bits as an int -- 32 bits. But it allows for a greater range of values, far greater than the range of int values. However, the precision is fixed at 24 bits (23 "mantissa" bits, plus 1 implied 1 bit). At the value of about 63,000,000, the precision is greater than 1. You can verify this with the Math.ulp method, which gives the difference between 2 consecutive values.

The code

System.out.println(Math.ulp(63000000.0f));

prints

4.0

You can use double values for a far greater (yet still limited) precision:

System.out.println(Math.ulp(63000000.0));

prints

7.450580596923828E-9

However, you can just use ints here, because your values, at about 63 million, are still well below the maximum possible int value, which is about 2 billion.

like image 81
rgettman Avatar answered Feb 15 '23 04:02

rgettman