Files
almond-bench/mandelbrot.c
T
2026-07-18 00:16:52 +02:00

76 lines
1.6 KiB
C

#include "stdio.h"
#include "math.h"
#include "stdint.h"
#define MAX_DEPTH 50
#define WIDTH 3
#define HEIGHT 2
/////////////////////
// complex numbers //
/////////////////////
typedef struct Complex {
double real, imag;
} Complex;
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);
}
////////////////
// mandelbrot //
////////////////
Complex f(Complex z, Complex c) {
return cx_add(cx_square(z), c);
}
////////////////
// ppm-writer //
////////////////
typedef struct Color {
uint8_t r, g, b;
} Color;
void write_ppm(char *path, Color img[HEIGHT * WIDTH]) {
FILE *fptr;
fptr = fopen(path, "w");
fprintf(fptr, "P3\n%d %d\n255\n", WIDTH, HEIGHT);
for (int i = 0; i < WIDTH * HEIGHT; i++) {
fprintf(fptr, "%d %d %d\n", img[i].r, img[i].g, img[i].b);
}
fclose(fptr);
}
// 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() {
Color img[WIDTH * HEIGHT] = {
(Color){255, 0, 0}, (Color){0, 255, 0}, (Color){0, 0, 255},
(Color){255, 0, 0}, (Color){0, 255, 0}, (Color){0, 0, 255}
};
write_ppm("test.ppm", img);
return 1;
}