5

This code print -46 when we cast a float to int,

This is because the information was lost during the conversion from type int to type float.

int i = 1_234_567_890;
float f = i;
System.out.println(i - (int)f);   //print  -46
System.out.println(i - f);        //print 0.0

How can one know about loss of precision while using float and double?

How can we know the result when we analyze the code before testing it ?

Med Elgarnaoui
  • 1,612
  • 1
  • 18
  • 35
  • you can use `Math.ulp()` to get an idea of what error to expect (e.g. `Math.ulp((float) 1_234_567_890) = 128.0`) - otherwise you must understand the IEEE-754 standard – user85421 Nov 13 '19 at 14:04

1 Answers1

2

The float representation is quite different from the integer representation.

Here you can see this specification (4.2.3. Floating-Point Types)

Here you can see Integer representation

Floating-Point representation uses sign, exponent and mantissa and float has

  • Sign (1 bit)
  • Exponent (8 bits)
  • Mantissa (23 bits)

With this, the maximun value that float can represent is: 340,282,346,638,528,860,000,000,000,000,000,000,000.000000

The maximun value that long can represent is 9,223,372,036,854,775,807

The maximun value that int can represent is: 2,147,483,647

Therefore, during the conversion from float to long or integer, the lost information can be of many orders of magnitude.

During the integer to float conversion you can lose up to 64u. of detail,It depends on the value. For example:

int i = 1_073_741_888;
float f = i;
System.out.println(i - (int)f);   //print  64
System.out.println(i - f);        //print 0.0

And

int i = 1_073_742_016;
float f = i;
System.out.println(i - (int)f);   //print  -64
System.out.println(i - f);        //print 0.0

The binary-integer representation of this values are:

  • 1_073_741_888: 1000000000000000000000001000000
  • 1_073_742_016: 1000000000000000000000011000000

The least significant bits are rounded when the value is greather than 16777216 (2^24 because of float's mantissa size -23 bits-).

David Pérez Cabrera
  • 4,960
  • 2
  • 23
  • 37