Skip to content

Instantly share code, notes, and snippets.

@rygorous
Created January 23, 2015 23:33
Embed
What would you like to do?
Trivial hand-rolled complex class
struct complexf
{
float re;
float im;
complexf() {}
complexf(float r) : re(r), im(0.0f) {} // would love to make this explicit, but std::complex doesn't.
complexf(float r, float i) : re(r), im(i) {}
};
complexf operator + (complexf const a, complexf const b) { return complexf(a.re + b.re, a.im + b.im); }
complexf operator - (complexf const a, complexf const b) { return complexf(a.re - b.re, a.im - b.im); }
complexf operator * (complexf const a, complexf const b) { return complexf(a.re*b.re - a.im*b.im, a.re*b.im + a.im*b.re); }
complexf &operator += (complexf &a, complexf const b) { a.re += b.re; a.im += b.im; return a; }
complexf &operator -= (complexf &a, complexf const b) { a.re -= b.re; a.im -= b.im; return a; }
complexf &operator *= (complexf &a, complexf const b) { a = a * b; return a; }
// HACK to get drop-in compat with std::complex
namespace std
{
float real(complexf const a) { return a.re; }
float imag(complexf const a) { return a.im; }
complexf conj(complexf const a) { return complexf(a.re, -a.im); }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment