| 1 | #ifndef VILE_COMPLEX_MATH_H |
| 2 | #define VILE_COMPLEX_MATH_H |
| 3 | #include <complex.h> |
| 4 | #include <string.h> |
| 5 | /* Keep the platform ABI inside this header; V exchanges two ordinary doubles. |
| 6 | * C11 6.2.5p13 specifies the array-of-two-real complex representation. |
| 7 | * Microsoft's documented CRT equivalent is _Dcomplex constructed by _Cbuild. |
| 8 | */ |
| 9 | typedef struct VileComplexParts { double re; double im; } VileComplexParts; |
| 10 | #if defined(_MSC_VER) |
| 11 | typedef _Dcomplex VileNativeComplex; |
| 12 | static inline VileNativeComplex vile_build_complex(double re, double im) { |
| 13 | return _Cbuild(re, im); |
| 14 | } |
| 15 | #else |
| 16 | typedef double _Complex VileNativeComplex; |
| 17 | static inline VileNativeComplex vile_build_complex(double re, double im) { |
| 18 | double parts[2] = { re, im }; |
| 19 | VileNativeComplex result; |
| 20 | memcpy(&result, parts, sizeof result); |
| 21 | return result; |
| 22 | } |
| 23 | #endif |
| 24 | /* Do not leak complex.h's convenience macros into compiler-generated code. */ |
| 25 | #ifdef I |
| 26 | #undef I |
| 27 | #endif |
| 28 | #ifdef complex |
| 29 | #undef complex |
| 30 | #endif |
| 31 | static inline VileComplexParts vile_complex_math(int operation, double re, |
| 32 | double im, double power_re, double power_im) { |
| 33 | VileNativeComplex z = vile_build_complex(re, im); |
| 34 | VileNativeComplex answer; |
| 35 | switch (operation) { |
| 36 | case 0: answer = cexp(z); break; |
| 37 | case 1: answer = clog(z); break; |
| 38 | case 2: answer = csin(z); break; |
| 39 | case 3: answer = ccos(z); break; |
| 40 | case 4: answer = ctan(z); break; |
| 41 | case 5: answer = casin(z); break; |
| 42 | case 6: answer = catan(z); break; |
| 43 | case 7: answer = csqrt(z); break; |
| 44 | default: answer = cpow(z, vile_build_complex(power_re, power_im)); break; |
| 45 | } |
| 46 | VileComplexParts result = { creal(answer), cimag(answer) }; |
| 47 | return result; |
| 48 | } |
| 49 | #endif |
| 50 | |