Instead, this operation returns -1.IND, since sqrt(-1)
returns -1.IND. Does the domain error mentioned on the C++ reference that this sqrt returns for negative values not retain the info that this is actually i?
Is there some way to perform this operation for all negative numbers, so that it returns the correct value, i.e. pow(sqrt(-36), 2)
will return -36?
You can use std::complex to achieve your goal, like this:
Output:
Note that std::sqrt(std::complex) is used here.
The reason behind the behaviour you encountered is the signatures of sqrt, namely:
which means that no matter which prototype will be used, you are getting nothing better than a
nan
(or a +-inf), since the return types can not support the imaginary part. That's whystd::complex
exists.So,
sqrt(-1)
will be replaced by anan
probably, which can not be treated bypow()
, so that -1 remains intact, because of the exponent. As a result the information is already lost after the call tosqrt()
andpow()
can do nothing about it.