user1387866
user1387866

Reputation: 3024

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?

Upvotes: 4

Views: 719

Answers (2)

Adrian Mole
Adrian Mole

Reputation: 51894

Since C++14, you can use the complex literal ""i to specify (only) the imaginary part of a complex number. Thus, for i you can use 1i.

Upvotes: 3

user14215102
user14215102

Reputation:

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;

Upvotes: 10

Related Questions