Skip to main content
GameDev.net gamedev.net
🔒 Locked

== comparison not working

Started by KingofNoobs Dec 13, 2012 at 9:39 AM 8 replies 3.4k views
Original Post
KingofNoobs
KingofNoobs
Hello all,

I have the following code that works in case (2) but not in case (1). Can anyone explain this to me? This could be the cause of many of my more subtle bugs.

int main()
{
sf::Window gameWindow(sf::VideoMode::GetMode(0), "Block Buster",sf::Style::Fullscreen);
uint32_t VideoModesCount = sf::VideoMode::GetModesCount();
for(uint32_t i = 0; i < VideoModesCount; ++i)
{
sf::VideoMode Mode = sf::VideoMode::GetMode(i);
float sixteenByNine = (float)16/9;
float aspectRatio = (float)Mode.Width / Mode.Height;

(1) if((float)((float)Mode.Width / Mode.Height) == ((float)16/9))
(2) if(aspectRatio == sixteenByNine)
std::cout << "Video Mode " << i << ":\tWidth: " << Mode.Width
<<"\tHeight: " << Mode.Height << "\tBpp: " << Mode.BitsPerPixel
<< std::endl;
}
// ...
return EXIT_SUCCESS;
}


Is there some weird truncation that is happening when I am directly comparing the variables inside the if() statement?

Thanks for your help.

- Dave Ottley
Ectara
Ectara
Floating point inaccuracy; one should not directly test for equality between floating point numbers.
C0lumbo
C0lumbo
TBH, the two options look equivalent to me, so I don't know why your results are inconsistent, but I'd recommend that you never try to compare the result of floating point calculations using ==. In general, instead of:

if (fA == fB)

You should use something like.

if (fabsf(fA - fB) < 0.0001f)

Because you almost always have precision errors in any floating point calculation and even if it works in debug, it might not work in release because the floating point operations can be rearranged to produce slightly different results.
caldiar
caldiar
Ectara's right. Removing the poorly thought out suggestion.
Ectara
Ectara

You could also check the width and height to see if they're multiples of 16 and 9 respectively such as:


if( ((Mode.Width % 16) == 0) && ((Mode.Height % 9) == 0))
{
std::cout << "Video Mode " << i << ": Width: " << Mode.Width
<<" Height: " << Mode.Height << " Bpp: " << Mode.BitsPerPixel
<< std::endl;
}


Almost, but the important part is the ratio: 32 by 9 is not a 16:9 ratio.
caldiar
caldiar

Almost, but the important part is the ratio: 32 by 9 is not a 16:9 ratio.


Well spotted! Perhaps a sign for me to turn off the computer for the night and go to bed.
Ectara
Ectara

Well spotted! Perhaps a sign for me to turn off the computer for the night and go to bed.

Happens to everyone every now and again.

Personally, I used an enum for preset aspect ratios, with an extra value to signify that it should calculate it from the width and height.

I think that if you know the ranges for the width and height, and you need determinism, you could try fixed point math.

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.