0

Possible Duplicate:
Strange floating-point behaviour in a Java program

I came across this weird phenomenon in Java. Try this statement in a Java program:

System.out.print(4.0-3.1);

The output will be 0.8999999

Why does this happen? And how can it be changed?

aman_novice
  • 1,027
  • 3
  • 13
  • 31
  • Wiered title for your question. I vote it down. – user unknown Feb 04 '11 at 06:25
  • 1
    @user unknown: Editing the title to correct an obvious typo didn't occur to you? – JUST MY correct OPINION Feb 04 '11 at 06:27
  • The title is still terrible even without any typo. Granted, you can't know what is wrong (or indeed what behaves as specified) before you've been answered, but mentioning "floating-point" would be a good start. The website may even be able to point out that your question is a duplicate without human intervention then. – Pascal Cuoq Feb 04 '11 at 06:36
  • @JUST MY correct OPINION: the typo is on my side, but pascal understood my concern. – user unknown Feb 04 '11 at 08:32

5 Answers5

5

I recommend reading What Every Scientist Should Know About Floating-Point Arithmetic. This is standard behavior for floating point math. Most systems (including Java) use IEEE 754 as the standard representation for floating point numbers. Exact, numerical values are not always perfectly represented by this standard, so you often see slight numerical inconsistencies when printing, as you found here.

Reed Copsey
  • 554,122
  • 78
  • 1,158
  • 1,373
4

This is a typical floating point result runded.

You get different results from Float and Double :

System.out.println(4.0f-3.1f);
System.out.println(4.0d-3.1d);

Output:

0.9000001
0.8999999999999999

This is because 0.1 cannot be represented evenly in base 2, and cause a loss of precision. For example :

System.out.println(2.0f-1.9f);
System.out.println(2.0d-1.9d);

Should both return 0.1 but in fact will output :

0.100000024
0.10000000000000009
Yanick Rochon
  • 51,409
  • 25
  • 133
  • 214
2

You will find your answer behind this link.

TL;DR summary: you will have to learn how floating point is represented in computing so you know why these things happen. This is an artifact of floating point representation and you alter it by not using float types if this kind of result is unacceptable to you.

JUST MY correct OPINION
  • 35,674
  • 17
  • 77
  • 99
2

floating point can't represent the value 0.1 or any multiple of 0.1 exactly. It is base 2 where the number system it is displayed in is base 10. There is some data lost when storing base 10 data in base 2 format.

Scott M.
  • 7,313
  • 30
  • 39
1

You are having fun with float types. But in binary. In the decimal system there are periodic numbers. Like 1/3 which is 1.33333 and so on. Some numbers in the decimal system are not periodic, but are periodic in the binary system.

Thus calculation is always inaccurate when there is the possibility of periodic numbers.

yankee
  • 38,872
  • 15
  • 103
  • 162