I'm copying a script from matlab into a c++ function. However, I constantly get different result for the exp function. For example, following snippet:
std::complex<double> final_b = std::exp(std::complex<double>(0, 1 * pi));
should be equivalent to the MATLAB code
final_b = exp(1i * pi);
But it isn't. For MATLAB, I receive -1 + 0i (which is correct) and for c++, I get -1 + -2.068231e-013*i.
Now I thought at the beginning this is just a rounding error of sorts, but for the actual script I'm using, which has bigger complex exponentials, I get completely different numbers. What is the cause of this? How do I fix this?
Edit: I've manually tried calculating the exponential with eulers formula
exp(x+iy) = exp(x) * (cos(y) + i*sin(y))
and get the same wonky results in c++
That is called floating point approximation (or imprecision):
If you include the header cfloat
there are some definitions. In particular, DBL_EPSILON
, which is the smallest number that 1.0 + DBL_EPSILON != 1.0
, which is usually 1e-9
(and -2.068231e-013
is much smaller than that. If you do the following piece of code, you can check if it is zero or not:
// The complete formula is std::abs(a - b), but since b is zero, I am ommiting it
if (std::abs(number.imag()) < DBL_EPSILON) {
// The number is either zero or very close to zero
}
For example, you can see the working code here: http://ideone.com/2OzNZm