Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing floating point numbers in C

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?

like image 351
nick_name Avatar asked Aug 10 '11 09:08

nick_name


People also ask

Can we compare two floating point numbers in C?

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.

Can we use == to compare two float values?

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.

How do you compare floats?

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.

Why do we never use == to compare floating point numbers?

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 !=


2 Answers

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.

like image 168
Steve Jessop Avatar answered Sep 29 '22 14:09

Steve Jessop


You can do a range. Like -0.00001 <= x <= 0.00001

like image 41
theknut Avatar answered Sep 29 '22 15:09

theknut