I’m trying to write std::complex
as an HLSL library. For this, I set out to implement the most basic functionality, starting with arithmetic operators. For finite numbers, all is well as expected. But things get weird at infinity. I won’t be touching any HLSL here, it’s all C++. All the following code was ran on Godbolt.
If I run the following code
std::complex<float> a(-3.0, 4.0);
std::complex<float> inf(1.0f / 0.0f, 0.0f);
a /= inf;
std::cout << a << std::endl;
Then the output will be (-0,0)
, which is expected. To implement this in HLSL I copied the definition for operator/=
found here (same gcc version as Godbolt to make sure).
Now running this code:
std::complex<float> a(-3.0, 4.0);
std::complex<float> inf(1.0f / 0.0f, 0.0f);
float r = a.real() * inf.real() + a.imag() * inf.imag();
float n = std::norm(inf);
float imag = (a.imag() * inf.real() - a.real() * inf.imag()) / n;
float real = r / n;
std::cout << std::complex<float>(real, imag) << std::endl;
The output is now (-nan, -nan)
which is different than what I got from just doing /=
, but is what I expect from reading the code
Is the STL doing something I’m not seeing in the source code, like some sort of sanity check? What am I missing?