This is no doubt simple, but how can I check if a double contains an integral value?
This is a discussion on Check to intiness within the C++ Programming forums, part of the General Programming Boards category; This is no doubt simple, but how can I check if a double contains an integral value?...
This is no doubt simple, but how can I check if a double contains an integral value?
"If you tell the truth, you don't have to remember anything"
-Mark Twain
Test against INT_MIN and INT_MAX or 0 and UINT_MAX in <climits>, or the equivalent templates from numeric_limits in <limits>. But beware testing for equality with floating-point, it's a pain to get right.
My best code is written with the delete key.
I've solved it: put the double's value into an int, then check equality of the original double with the new int typecasted as a double. If they are equal, then the original double is an integer. Gotta love truncation.
"If you tell the truth, you don't have to remember anything"
-Mark Twain
>put the double's value into an int
And what if the double's value is out of range for an int? Signed overflow is undefined.
My best code is written with the delete key.
You could also have a "imperfect" floating point value.
I didn't compile this, but...basically this just ensures the value is in the range of an int, casts it, and then restores it to the original magnitude. The pointers are there to save us from having to use two separate loops (one for greater, one for less than zero).
Code:double integral(double n) { int f = 0; double m, * l, * r; if(n > 0) { m = INT_MAX; l = &n, r = &m; } else { m = INT_MIN; l = &m, r = &n; } while(*l > *r) { ++f; n -= m; } n = (int)n; if(f) { n += f * m; } return n; } bool is_integral(double n) { return n-integral(n) == 0; }
Code:#include <cmath> #include <complex> bool euler_flip(bool value) { return std::pow ( std::complex<float>(std::exp(1.0)), std::complex<float>(0, 1) * std::complex<float>(std::atan(1.0) *(1 << (value + 2))) ).real() < 0; }
Neat. Thanks.
"If you tell the truth, you don't have to remember anything"
-Mark Twain