0

I'm currently in the process of learning Java. I have just run the following line in Eclipse in Win7 using jre1.8.0_25:

System.out.println(4.5 * 7.9);

The console output is: 35.550000000000004

I'm just wondering why the output is wrong.

user207421
  • 305,947
  • 44
  • 307
  • 483
desiguel
  • 505
  • 3
  • 10

3 Answers3

1

When looking for accuracy, doubles are not the best choice, as they are actually not as perfect as they may seem due to some limitations in their design.

See http://introcs.cs.princeton.edu/java/91float/

kirbyquerby
  • 735
  • 5
  • 16
1

It's not only a Java issue (feature?), it's a common issue for all languages with floating point arithmetics. It's based on IEEE 754 standard, in case you're interested.

kamituel
  • 34,606
  • 6
  • 81
  • 98
1

It's because of loss of precision due to operations made by the computer in binary. You can see an explanation of it here.

AxiomaticNexus
  • 6,190
  • 3
  • 41
  • 61
  • 1
    It's also because of imprecision in the input literals. 7.9 cannot be represented accurately in floating-point. – user207421 Jan 30 '15 at 00:40