feat(c): simple complex numbers and divergence
This commit is contained in:
+30
-2
@@ -1,16 +1,44 @@
|
||||
#include "stdio.h"
|
||||
#include "math.h"
|
||||
|
||||
#define MAX_DEPTH 50
|
||||
|
||||
typedef struct {
|
||||
double real;
|
||||
double imag;
|
||||
} Complex;
|
||||
|
||||
void complex_print(Complex z) {
|
||||
void cx_print(Complex z) {
|
||||
printf("%f + %f i", z.real, z.imag);
|
||||
}
|
||||
|
||||
static inline Complex cx_square(Complex z) {
|
||||
return (Complex){z.real * z.real - z.imag * z.imag, 2 * z.real * z.imag};
|
||||
}
|
||||
|
||||
static inline Complex cx_add(Complex z1, Complex z2) {
|
||||
return (Complex){z1.real + z2.real, z1.imag + z2.imag};
|
||||
}
|
||||
|
||||
static inline double cx_abs(Complex z) {
|
||||
return sqrt(z.real * z.real + z.imag * z.imag);
|
||||
}
|
||||
|
||||
Complex f(Complex z, Complex c) {
|
||||
return cx_add(cx_square(z), c);
|
||||
}
|
||||
|
||||
// return iteration count, MAX_DEPTH if diverge
|
||||
int diverge(Complex c) {
|
||||
int counter = 0;
|
||||
Complex z = {0.0, 0.0};
|
||||
for (z = f(z, c); cx_abs(z) < 2; counter++)
|
||||
if (counter > MAX_DEPTH) return MAX_DEPTH;
|
||||
return counter;
|
||||
}
|
||||
|
||||
int main() {
|
||||
Complex z = {2.0, 4.0};
|
||||
complex_print(z);
|
||||
cx_print(z);
|
||||
return 1;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user