Last active
June 8, 2025 18:50
-
-
Save Rizwan-Hasan/524666c033f47eb0bb40aec88d3b3296 to your computer and use it in GitHub Desktop.
A basic implementation of Julia Set. For more: https://en.wikipedia.org/wiki/Julia_set
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import time | |
from PIL import Image | |
# Area of complex space to investigate | |
x1, x2, y1, y2 = -1.8, 1.8, -1.8, 1.8 | |
c_real, c_imag = -0.62772, -0.42193 | |
def calculate_z_serial_purepython(maxiter, zs, cs): | |
"""Calculate output list using Julia update rule""" | |
output = [0] * len(zs) | |
for i in range(len(zs)): | |
n = 0 | |
z = zs[i] | |
c = cs[i] | |
while abs(z) < 2 and n < maxiter: | |
z = z * z + c | |
n += 1 | |
output[i] = n | |
return output | |
def calc_pure_python(desired_width, max_iterations): | |
"""Create a list of complex coordinates (zs) and complex parameters (cs), | |
build Julia set, and generate image with PIL""" | |
x_step = (x2 - x1) / desired_width | |
y_step = (y1 - y2) / desired_width | |
x = [] | |
y = [] | |
ycoord = y2 | |
while ycoord > y1: | |
y.append(ycoord) | |
ycoord += y_step | |
xcoord = x1 | |
while xcoord < x2: | |
x.append(xcoord) | |
xcoord += x_step | |
zs = [] | |
cs = [] | |
for ycoord in y: | |
for xcoord in x: | |
zs.append(complex(xcoord, ycoord)) | |
cs.append(complex(c_real, c_imag)) | |
print("Length of x:", len(x)) | |
print("Total elements:", len(zs)) | |
start_time = time.time() | |
output = calculate_z_serial_purepython(max_iterations, zs, cs) | |
end_time = time.time() | |
secs = end_time - start_time | |
print(calculate_z_serial_purepython.__name__ + " took", secs, "seconds") | |
assert sum(output) == 33219980 | |
# Generate image using PIL | |
image = Image.new("RGB", (desired_width, desired_width)) | |
pixels = image.load() | |
for i in range(desired_width): | |
for j in range(desired_width): | |
value = output[i * desired_width + j] | |
color = int(value * 255 / max_iterations) | |
pixels[j, i] = (color, color, color) # grayscale | |
image.save("julia_set.png") | |
print("Image saved as julia_set.png") | |
if __name__ == "__main__": | |
calc_pure_python(desired_width=1000, max_iterations=300) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Output
Output
julia_set.png