Sign in to follow this  

Casting double to int, when it is reasonable safe?

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

This topic is 3501 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.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this