Skip to content

Instantly share code, notes, and snippets.

@abhijit-c
Last active January 25, 2020 18:34
Show Gist options
  • Save abhijit-c/7b98d510c7121013e566753a3af03d4c to your computer and use it in GitHub Desktop.
Save abhijit-c/7b98d510c7121013e566753a3af03d4c to your computer and use it in GitHub Desktop.
Code for animating the Julia set (f(z) = z^2 + c) for many different choices of c. Needs to be run in a shell (for the system command) with the convert utility.
#include <complex.h>
#include <math.h>
#include <omp.h>
#include <stdio.h>
#include <stdlib.h>
// Adapted from https://batchloaf.wordpress.com/2013/02/10/another-julia-set-animation/
#define BOX_SIZE 2.0
#define NUM_FRAMES 240
int main(int argc, char **argv)
{
if (argc != 2)
{
perror("USAGE: ./julia.out resolution \n");
return -1;
}
int resolution = atoi(argv[1]);
int w = resolution; double w_grid[w];
for (int i = 0; i < w; i++) { w_grid[i] = -BOX_SIZE + 2*i*BOX_SIZE/w; }
int h = resolution; double h_grid[h];
for (int i = 0; i < h; i++) { h_grid[i] = -BOX_SIZE + 2*i*BOX_SIZE/h; }
#pragma omp parallel for
for (int frame = 1; frame <= NUM_FRAMES; frame++)
{
char filename[50]; sprintf(filename, "%05d.pgm", frame);
FILE* current_frame = fopen(filename, "w");
fprintf(current_frame, "P2\n\n%d %d\n255\n", w, h);
double theta = frame*(2*M_PI/NUM_FRAMES);
for (int i = 0; i < w; i++)
{
for (int j = 0; j < h; j++)
{
complex double z = w_grid[i] + I*h_grid[j];
complex double c = 0.7885*cexp(I*theta);
int n = 255;
while (cabs(z) < 10 && n > 0)
{
z = cpow(z,2) + c;
n = n - 5;
}
fprintf(current_frame, "%d ", n);
}
fprintf(current_frame, "\n");
}
fclose(current_frame);
char cmd_buffer[50];
sprintf(cmd_buffer, "convert %05d.pgm %05d.png", frame, frame);
system(cmd_buffer);
printf("%s\n", filename);
}
system("convert -delay 5 -loop 0 *.png animation.gif");
system("make clean");
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment