I have a code in which I perform many operations of the form
double z_sq = pow(abs(std::complex<double> z), 2);
to calculate |z|² of a complex number z, where performance and precision are my major concerns. I read that the pow()
function of C++ converts int
exponents to double
and thus introduces numerical errors apart from also having worse performance than x*x in general (discussed here for real numbers). Similarly, the std::pow()
method of <complex>
converts the exponent to std::complex<double>
unnecessarily.
My first question is how to implement the complex square Re²+Im² or zz* with best-possible performance and precision. I thought about doing something like
double complex_square1(std::complex<double> z) {
double abs_z = abs(z);
return abs_z * abs_z;
}
or (which gives a type error, but would be the most straight-forward way, I can think of)
double complex_square2(std::complex<double> z) {
return z * conj(z);
}
My second question is, whether for many (10^14) such operations, the function calls can decrease performance noticably. So would it be better in the case of complex_square1
to write abs(z) * abs(z)
into the .cpp file instead of defining a function for it? Are there any other better ways to do it?