tyr
tyr

Reputation: 139

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?

Upvotes: 2

Views: 284

Answers (2)

tofro
tofro

Reputation: 6063

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. This has absolutely nothing to do with precision - 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.

Upvotes: 4

Eli Sadoff
Eli Sadoff

Reputation: 7308

There's nothing about taking a float from the keyboard that makes it inherently less precise than any other float. Having said that, in taking a float from the keyboard, you run the risk of two numbers that are different being stored as the same value as the difference between the two numbers is less than the epsilon for single precision floats. However, this is no different from any other usage of floats. In summary, a float acquired from scanf is no different than any other float, and any safety measures you would or wouldn't normally use should be used with these floats as well.

Upvotes: 0

Related Questions