c++ - Can division by non-zero still create a nan / infinity -


i have number might zeros. divide number want test if it's 0 prevent nan's , infinitys. possible still create nans / infinity because of rounding errors within division?

double x; // might 0 double y;  if(x != 0) return y / x; 

edit

thanks responses. i'll add subquestions then.

1) assuming neither x nor y nan / +inf or -inf, division results in -inf / +inf result in more cpu cycles or other unwanted behaviour? (could crash?)

2) there way prevent division resulting in infinity? using offsets , on.

can division non-zero still create nan / infinity

yes.

if ieee-754 followed then:

  • if either operand nan, result nan.
  • if both numerator , denumerator infinity, result nan.
  • if numerator infinity, result infinity.
  • if division small denumerator (or large numerator) overflows, result may infinity, depending on current rounding mode.

rules of other representations may different.


2) there way prevent devision resulting in infinity

this should go long way in preventing that:

#include <cfenv> #include <cassert> #include <cmath> #include <limits>  // ...  static_assert(std::numeric_limits<decltype(x)>::is_iec559, "unknown floating point standard."); #pragma stdc fenv_access on int failed = std::fesetround(fe_towardzero); assert(!failed); if(x != 0 && std::isfinite(x) && std::isfinite(y))     return y / x; else     throw std::invalid_argument("informative message"); 

some compilers may need non-default options enable full ieee 754 compliance (-frounding-math on gcc).


Comments

Popular posts from this blog

jOOQ update returning clause with Oracle -

java - Warning equals/hashCode on @Data annotation lombok with inheritance -

java - BasicPathUsageException: Cannot join to attribute of basic type -