Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Different behaviour while comparing double [duplicate]

Tags:

java

c

Hello I know that computer is limited by number precision, and some numbers cannot be represented accurately in binary system. That’s why I'm asking why such comparison

(0.1*3) == 0.3

in Java language evaluates to false while in C it evaluates to true, for me the Java behavior is a little bit more intuitive. Any of provided answers does not answer my question why they have different behaviors, since both use IEEE 754 standard.

@update I was using ideone to test condition.

like image 849
whd Avatar asked Apr 05 '16 13:04

whd


1 Answers

Comparing floating-point values is notoriously imprecise.

For any given floating-point operation, you are guaranteed an accuracy only down to DBL_EPSILON / Double.Epsilon. Any bits that exist beyond this precision are artifacts of the arithmetic operations and should be ignored.

Different programs, and certainly different languages, will implement such comparisons differently (obviously). If you can manage to compare values to a specific accuracy, i.e., a specific number of bits within the representational range of the values (e.g., 52 bits or less for IEEE double-precision float), you stand a better chance of getting identical results.

Reference (added April 2016)

Here is the oft-cited explanation of floating-point numbers and how they behave:
What Every Computer Scientist Should Know About Floating-Point Arithmetic

like image 83
David R Tribble Avatar answered Oct 02 '22 14:10

David R Tribble