Jump to content
  • Advertisement
Sign in to follow this  
gdbetb

Casting double to int, when it is reasonable safe?

This topic is 3719 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

I'd like trying implement a simple game using C. One of the first problems I have to solve is how to rotate points in a plane. The linear algebra gives all answers, but computers do not understand real numbers. So I am using doubles. The double (at least in my machine) has twice as bit of a int. But it also tries to emulate a much larger set... And so I was wondering, it when it is safe cast a double in a int? It is in the reasonable magnitude of numbers that are the screen coordinates? Thanks everyone.

Share this post


Link to post
Share on other sites
Advertisement
It should always be safe to cast to an int in the sense that it won't horribly crash or throw exceptions or anything like that. Casting a double that's too large or too small to fit an int will probably just produce INT_MAX or INT_MIN (2^31-1 and -2^31 on 32-bit systems). If the double is between those, it will be rounded to either of the nearest ints (depending on the rounding mode, usually the one closer to zero).

Also, floating points don't 'emulate' anything. They are much like the scientific notation 123.4E56 with a certain precision for the mantissa and a range for the exponent.

Share this post


Link to post
Share on other sites
Quote:
Original post by gdbetb
And so I was wondering, it when it is safe cast a double in a int?
It is in the reasonable magnitude of numbers that are the screen coordinates?
Assuming by "int" you mean a 32-bit signed integer, you have a range of about +/- 2 billion, with no fractional component.
So, so long as your double is in the range +/- 2 billion, and you don't mind losing the fractional component, it's safe. Although you'll normally want to do an explicit cast to prevent compiler warnings.

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!