class Q44
{
public static void main(String[] args)
{
int i=0, y;
float j=0;
while(true)
{
j = i;
y=(int)j;
if( (y-i) != 0)
{
System.out.println("i = " + i);
break;
}
i++;
}
i = -1;
while(true)
{
j = i;
y=(int)j;
if( (y-i) != 0)
{
System.out.println("i = " + i);
break;
}
i--;
}
}
}
i = 16777217
i = -16777217
Floating points are first converted to form : N = ± (1.b1b2b3b4 ...)2 x 2+E
The left most one is not stored(always 1). The bits b1b2b3 etc.,(upto 23 bits) is what goes into the mantissa part. Hence, the first maximum bit for an integer can be 24 successive one's. (23 One's for mantissa and one implicit 1). 24 successive one corresponds to the number : 16777215. The next number is 16777216 for which the bit pattern is : 1000000000000000000000000
ie., one followed by 24 zero. So, even though the 24th zero is not stored, precision is not lost. Because when we convert back it is restored. So, the maximum integer without losing precision that can be converted back from float is now : 16777216
Now, if we consider the next number (16777217) for which the bit pattern is : 1000000000000000000000001. This has 1 followed by 23 zeros and then a 1. Because of 1 in the 24th bit, the 23rd bit will be rounded to 1 and the first precision loss comes for this number. Thus, the number 16777217 is the first integer number which when converted to float and converted back to integer will lose the precision as proved by the output of the above code.
No comments:
Post a Comment