tyr tyr - 1 year ago 107
C Question

Comparing floats in C

Assume you're given this excerpt of code:

Example 1:

printf("Enter two real numbers: ");
scanf("%f %f", &a, &b);

if (a == b) //do something

My question is: Is it necessary to use some "safety measures" when comparing floats directly taken from keyboard?

For instance if I'm given the similar code:

Example 2:

printf("Enter two real numbers: ");
scanf("%f %f", &a, &b);
float x = a / b + 2 * a / 3;
float y = b / a + 3 * a / 2;
if (x == y) //do something

I know I should be using:

fabs(x - y) < RefValue

for if's condition just to avoid potential occurence of false even if the result should be true. But do I have to do so in Example 1, too?

Answer Source

It's pretty safe to assume that two numbers entered from the keyboard using the same input method in the exact same character representation end up as the same binary number - After all, that's reproducibility, one of the most inherent traits of computer programs we rely on. The two numbers might be imprecise and not exactly represent the input, but they must be identical. In short, your Example 1 is valid.

It's even possible (but not guaranteed) that different character representations end up at the same binary number, which would be caused by the fact that not all decimal numbers have an exact representation in the internal FP format. That would not affect your comparison, though, as there is not much you can do about that except using a different internal representation.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download