I
I
Ivan Klimenko2016-09-18 00:55:14
C++ / C#
Ivan Klimenko, 2016-09-18 00:55:14

Is it correct to compare a real number with zero?

In fact, I know how to correctly compare real numbers, but I don’t understand how the following code will behave:

float x = 0.0;
...
if ( x == 0.0 ) { ... }

To be clear, assigning a null value to a variable occurs inside another function, and keeping track of this (for example, using flags) is not the best option: there is too much overhead. And it is necessary to check exactly for exactly zero value, because the logic of the program depends on it.
I would be grateful if you tell me about books that explain such subtleties =)

Answer the question

In order to leave comments, you need to log in

2 answer(s)
R
Rsa97, 2016-09-18
@yeswell

If it is the constant zero that is assigned, and not the result of any calculation, then comparison with zero is safe.

M
Mercury13, 2016-09-18
@Mercury13

So it's safe to compare. The only question is - can a zero appear during calculations and will it not break the logic of the program?
It is better, of course, not to use 0.0, but 0.0f for this.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question