• Advertisement
Sign in to follow this  

Quick dividing by a float question

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

(In c++) When dividing by a float, is it worth checking if the float is equal to 0, if it was would it throw an exception or something?

Share this post


Link to post
Share on other sites
Advertisement
No, dividing by 0.0 yields plus or minus infinity which floats are able to represent.

Share this post


Link to post
Share on other sites
Is it worth it? Yes.
Do you need to? No.

General recomendation is to not use exceptions for normal control flow. So if you expect your value to be 0 frequently, or if your value can be valid with value of 0, then check it.

Exceptions would be more suitable in cases where the divisor should, or even "could" not be 0.

Share this post


Link to post
Share on other sites
It also depends on what you're going to do with the result.

I've had code that shoved essentially random numbers into some complicated set of floating point operations. There were any number of places where there was potential to divide by zero. I didn't check anything until I got the final result out and then checked that instead.

On the other hand if getting a bad result out is more problematic in your app then that sort of fast & loose philosophy can make it harder to debug why you're getting division by zero in the first place.

Floating-point division by zero will not automatically throw an exception of any sort on architectures I'm familiar with. I don't know if the standard says anything about this sort of thing - at least for C/C++, if you're programming in Ada or something stricter the story would probably be different.

*Integer* division by zero is a completely different beast.

Share this post


Link to post
Share on other sites
Quote:
Original post by Anon Mike
Floating-point division by zero will not automatically throw an exception of any sort on architectures I'm familiar with. I don't know if the standard says anything about this sort of thing - at least for C/C++, if you're programming in Ada or something stricter the story would probably be different.

In C++ the results are undefined for both integer and floating point arithmetic. I've had pretty good luck with assuming floating pont division by zero goes to +/- infinity, but technically I can't assume that unless my compiler documentation says I can.

CM

Share this post


Link to post
Share on other sites
You can enable floating point exception is MSVC look here http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dv_vstechart/html/floapoint.asp

Share this post


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

  • Advertisement