Search code examples
c++c++14stdcomplex-numbers

Complex constant i in C++?


When writing C++ code, rather than:

double a, b;
...
std::complex<double> z = a + b * std::complex<double>(0, 1);

I would prefer to write something like:

std::complex<double> z = a + b * i;

I can see that C99 has macro I (https://en.cppreference.com/w/c/numeric/complex/I), but it can't be use with std::complex:

std::complex<double> z = a + b * I; // does not compile

Of course, I could define myself some constant for that purpose, but that constant must exist somewhere already in C++. What is it called?


Solution

  • The custom literal i (e.g. 1i), see example in https://en.cppreference.com/w/cpp/numeric/complex

    #include <complex>
    using namespace std::complex_literals;
    std::complex<double> z1 = 1i * 1i;