Skip to content

Instantly share code, notes, and snippets.

@SabinT
Created June 21, 2021 08:24
Show Gist options
  • Save SabinT/9ef2180db4b42c5eef368e4154bc6569 to your computer and use it in GitHub Desktop.
Save SabinT/9ef2180db4b42c5eef368e4154bc6569 to your computer and use it in GitHub Desktop.
Some complex number manipulation functions in HLSL (double precision)
double2 cartesianToPolar(double2 z)
{
return double2(length(z), atan2(z.y, z.x));
}
double2 polarToCartesian(double2 p)
{
return double2(p.x * cos(p.y), p.x * sin(p.y));
}
/**
* Computes e^z, where z = (x + i.y)
* e^z = e^x * (cosy + i.siny)
*/
double2 complexExp(double2 z) {
return exp(z.x) * double2(cos(z.y), sin(z.y));
}
// TODO port this to float as well
// (A + ib) ^ n
double2 complexPow(double2 z, double n) {
double r = length(z);
double angle = atan2(z.y, z.x);
return pow(r, n) * double2(cos(n * angle), sin(n * angle));
}
// TODO port this to float as well
// (a + ib) ^ (c + id) = e ^ (log(r)(c + id) + i * theta * (c + id))
double2 complexPow2(double2 c1, double2 c2) {
double r = length(c1);
double angle = atan2(c1.y, c1.x);
double2 cExp = double2(c2.x * log(r) - angle * c2.y, c2.x * c2.y + angle * c2.x);
return complexExp(cExp);
}
/**
* Computes natural log(z), where z = (x + i.y)
* log(z) = log(r) + i.theta
* where r = sqrt(x^2 + y^2)
* where theta = atan(y/x)
*/
double2 complexLog(double2 z) {
return double2(log(length(z)), atan2(z.y, z.x));
}
double2 complexMult(double2 a, double2 b){
return double2(a.x * b.x - a.y * b.y, a.x * b.y + a.y * b.x);
}
double2 complexDiv(in double2 a,in double2 b){
double x = dot(b, b);
return double2(a.x * b.x + a.y * b.y, a.y * b.x - a.x * b.y) / x;
}
double complexArg(double2 z) { return double(atan2(z.y, z.x)); }
double2 complexSin(double2 z) { return double2(sin(z.x) * cosh(z.y), cos(z.x) * sinh(z.y)); }
double2 complexCos(double2 z) { return double2(cos(z.x) * cosh(z.y), -sin(z.x) * sinh(z.y)); }
double2 complexTan(double2 z) { return double2(sin(2.0 * z.x)/(cos(2.0 * z.x) + cosh(2.0 * z.y)), sinh(2.0 * z.y)/(cos(2.0 * z.x) + cosh(2.0 * z.y))); }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment