Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assigning floating value to a double value

I was referring this Oracle documentation. While trying to execute the following,

 public static void main(String args[]){

    float f = 1.1f;
    double df = 1.1f;

    System.out.println("f=" + f);
    System.out.println("df=" + df);

    f = 1.5f;
    df = 1.5f;
    System.out.println("f=" + f);
    System.out.println("df=" + df);
 }

Output is

f  = 1.1
df = 1.100000023841858
f  = 1.5
df = 1.5

Why the second line of output is showing an approximate value. But not for fourth line. How the value is getting calculated?

like image 817
Nidheesh Avatar asked Feb 19 '14 09:02

Nidheesh


1 Answers

The difference is that 1.5 can be represented exactly in double - whereas 1.1 can't be represented exactly.

It's because of periodical digits, any (irreducible) fraction where the denominator has a prime factor that does not occur in the base requires an infinite number of digits that repeat periodically after a certain point. For example, in decimal 1/4, 3/5 and 8/20 are finite, because 2 and 5 are the prime factors of 10. But 1/3 is not finite, nor is 2/3 or 1/7 or 5/6, because 3 and 7 are not factors of 10. Fractions with a prime factor of 5 in the denominator can be finite in base 10, but not in base 2 - the biggest source of confusion for most novice users of floating-point numbers.

Squeezing infinitely many real numbers into a finite number of bits requires an approximate representation. Although there are infinitely many integers, in most programs the result of integer computations can be stored in 32 bits. In contrast, given any fixed number of bits, most calculations with real numbers will produce quantities that cannot be exactly represented using that many bits. Therefore the result of a floating-point calculation must often be rounded in order to fit back into its finite representation. This rounding error is the characteristic feature of floating-point computation.

Check here for more details

like image 69
Abimaran Kugathasan Avatar answered Oct 02 '22 16:10

Abimaran Kugathasan