danijar
danijar

Reputation: 34175

Is it safe to cast a float with value 0.0f to boolean?

I know that due to precision errors, a float varibale should be checked to equal a value always with some tolerance. But what's is that even the case if I manually set the float variable to 0.0f?

For example there is a function returning a distance.

float distance()
{
    float value;
    if(/* ... */)
    {
        // ...
        return value;
    }
    else return 0.0f;
}

Can I cast the result to bool safely?

if(distance())
{
   // ...
}

Upvotes: 2

Views: 2485

Answers (5)

David Heffernan
David Heffernan

Reputation: 612804

When you write:

if(distance())

you are checking whether the float is zero or not.

Your code is equivalent to

if(distance() != 0)

This is perfectly safe to do, and only you can determine whether or not it has the meaning that you require.

Upvotes: 10

Gabe
Gabe

Reputation: 86708

If you have an exact value that you expect, there's absolutely no reason not to compare against that exact value. It's only when you perform a computation and get an inexact result that it's unsafe to compare against an exact value. And you generally want to assume that any floating point computation will give an inexact result.

In your case, you're returning a constant, so it's safe to compare to a constant.

Another time you'd want to compare against an exact value is to avoid singularities. For example, x == 0.0 ? 1.0 : sin(x)/x.

Upvotes: 3

Oszkar
Oszkar

Reputation: 697

Technically, yes; 0.0f is representable by the IEEE 754 standard. However, the question is that will it be always zero, when you expect it to be and not the next floating point number.

I wouldn't do it, though.

Upvotes: 2

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385108

You're correct to worry about floating-point inaccuracy, but you're also correct to suppose that it isn't a problem in this case.

The likelihood of your computer storing 0.0f as anything other than precisely zero is astronomical, and a conversion of precisely floating-point zero to boolean is well-defined.

Upvotes: 1

Bill Lynch
Bill Lynch

Reputation: 81916

Basically, you're asking if you can assume that the following line won't fire.

assert(0.0f); 

Yes. You can assume that.

Upvotes: 2

Related Questions