简体   繁体   中英

std::exp giving different result than MATLAB exp for complex number

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM