I've got a double
that prints as 0.000000
and I'm trying to compare it to 0.0f
, unsuccessfully. Why is there a difference here? What's the most reliable way to determine if your double is zero?
Master C and Embedded C Programming- Learn as you goTo compare two floating point values, we have to consider the precision in to the comparison. For example, if two numbers are 3.1428 and 3.1415, then they are same up to the precision 0.01, but after that, like 0.001 they are not same.
Because comparing floats with == is problematic, it's unwise to use them as IDs; the names in your example code suggest that's what you are doing; long integers (longs) are preferred, and the de facto standard for IDs.
The compare() method of Float Class is a built-in method in Java that compares the two specified float values. The sign of the integer value returned is the same as that of the integer that would be returned by the function call. Parameters: The function accepts two parameters: f1: The first float value to be compared.
Because floating point arithmetic is different from real number arithmetic. Bottom line: Never use == to compare two floating point numbers. Here's a simple example: double x = 1.0 / 10.0; double y = x * 10.0; if (y !=
To determine whether it's close enough to zero that it will print as 0.000000
to six decimal places, something like:
fabs(d) < 0.0000005
Dealing with small inaccuracies in floating-point calculations can get quite complicated in general, though.
If you want a better idea what value you've got, try printing with %g
instead of %f
.
You can do a range. Like -0.00001 <= x <= 0.00001
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With