Jump to content
  • Advertisement
Sign in to follow this  
Endemoniada

In my Round() foolproof ?

This topic is 4877 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hi guys, Is this foolproof: int Round(double x) { if(x > 0.0) return (int)(x+0.5); else if(x < 0.0) return (int)(x-0.5); return 0; } It seems solid but maybe I'm missing something ? Thanks.

Share this post


Link to post
Share on other sites
Advertisement
Well, as long as you aren't dealing with monetary values, should be fine.

Share this post


Link to post
Share on other sites
Ok, I'm just completely guessing at this and have no idea if it is or is not true. Is it possible that ".5 + ??.5 < ?? + 1"? Basically, I'm wondering if the innacurate nature of floating point will make it so that the rounding function will sometimes go the wrong way. Of course, even if true it is completely nitpicky (but you did say foolproof).

Share this post


Link to post
Share on other sites
You'll only have problems if your double values are greater than the available precision. Without looking at the IEEE specification, I'm pretty much sure your function is fine for values MAX_INT/4 and lower. You might safe all the way up to MAX_INT (after which, it dosn't really matter, because you can't convert anyway).


Quote:
Is it possible that ".5 + ??.5 < ?? + 1"?

Because of the way floating point numbers are represented, 0.5 becomes "1/2" which can be exactly represented in binary (as "1/10").

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!