Tuesday, 15 July 2014

In current C++ and Java, double type and float type : if (x == 0.0) is correct? -



In current C++ and Java, double type and float type : if (x == 0.0) is correct? -

this question has reply here:

double arithmetic , equality in java 3 answers

in old knowledge: when want check whether double or float equal 0.0, should not write this:

double x = 0.0; if (x == 0.0) system.out.println("yes"); else system.out.println("no");

but several minutes ago, tried again, under java(1.7) , c++(apple llvm version 6.0), there no problem write that! have tried both "double" type , "float" type under java , c++, respectively.

my question:

did miss something, or can check double or float under current java , c++. if can, whether can under version of java , c++?

conclusion(based on helps): should not utilize "float == float or double == double" check whether 2 floats or 2 doubles equal(if want right answer), reasons in answers , comments below.

edition(first time): thank much help! 1 min ago, seek these under java(1.7), show "yes", seems really can it under current java!

float x = 0.0f; if (x == 0) system.out.println("yes"); else system.out.println("no"); float y = 100.0f - 50.0f*2.0f + 45.0f*3 - 135.0f; if (y == 0.0f) system.out.println("yes"); else system.out.println("no"); if (100.0f - 50.0f*2.0f + 45.0f*3 - 135.0f == 0.0f) system.out.println("yes"); else system.out.println("no");

edition(second time): have tried this, java shows "yes", (under java(1.7)). seek eliminate compiler's "pre-compute", , split computation several steps.

float = 100.0f; float b = 50.0f; float c = 2.0f; float bc = b * c; system.out.println("b*c = " + bc); float d = 45.0f; float e = 3.0f; float de = d * e; system.out.println("d*e = " + de); float f = 135.0f; float g = - bc + de - f; float h = 0.0f; if (g == h) system.out.println("yes"); else system.out.println("no");

edition(third time): give thanks @diegobasch's counterexample (for float == float): time java(1.7) shows "no".

float m = 0.37f - 0.36f; float n = 0.01f; if (m - n == 0.0f) system.out.println("yes"); else system.out.println("no");

the code legal. problem when you're doing calculations involving floating-point numbers, there rounding errors, , hence in many cases checking 0 (or checking 2 numbers equality) not work.

this code fine in language since haven't done cause rounding:

double x = 0.0; if (x == 0.0) system.out.println("yes"); else system.out.println("no");

this code may not fine, though:

double a1 = ...something...; double a2 = ...something...; double a3 = a1 / a2; double a4 = a3 * a2; double a5 = a4 - a1; if (a5 == 0.0) ...

even though mathematically a5 should 0, in practice == operation may homecoming false because of rounding.

this requires understanding of how floating-point handled in computer; has nil language or version of language. 1 reference what every computer scientist should know floating-point.

java c++ floating-point double

No comments:

Post a Comment