Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Float numbers in Java

Could anyone please me why the output of the following programme is not " different different"?

public static void main(String[] args)
{

float f1=3.2f;
float f2=6.5f;

if(f1==3.2)
System.out.println("same");
else
System.out.println("different");

if(f2==6.5)
System.out.println("same");
else
System.out.println("different");
}

o/p :different same

like image 645
Alvin Avatar asked May 29 '10 18:05

Alvin


People also ask

What is a float number example?

A floating point number, is a positive or negative whole number with a decimal point. For example, 5.5, 0.25, and -103.342 are all floating point numbers, while 91, and 0 are not.

Is 0.0 A float number?

'' If there is no minus zero, then 0.0 and -0.0 are both interpreted as simply a floating-point zero.

What is a float number type?

Integers and floats are two different kinds of numerical data. An integer (more commonly called an int) is a number without a decimal point. A float is a floating-point number, which means it is a number that has a decimal place. Floats are used when more precision is needed.


1 Answers

6.5 has a finite binary representation: 110.1

Any floating type with at least 4 significant bits can represent this number perfectly.

110.100000000000000000000 (float)
= 6.5

110.10000000000000000000000000000000000000000000000000 (double)
= 6.5

3.2 on the other hand has an infinite binary representation: 101.0011001100110011...

float and double don't have infinite precision and thus can only approximate this number :(

101.001100110011001100110 (float)
= 3.2000000476837158203125

101.00110011001100110011001100110011001100110011001101 (double)
= 3.20000000000000017763568394002504646778106689453125

As you can clearly see, these numbers are not the same!

like image 60
fredoverflow Avatar answered Sep 17 '22 03:09

fredoverflow