I wrote a python script that progressively scales an image from a rectangle to a triangle. It works. it should not. I discovered that in the for loop, the index starts at zero and is used as the denominator in the pixel position function. I discovered this weird behaviour when i tried to declare the variables outside the loop. Why is it working? did i break maths? have I discovered infinity? Where's my Nobel Prize?
ZeroDivisionError: division by zero
#!/usr/bin/python3
# Python 3.10.12
from PIL import Image, ImageChops
source_map = "rectangle.jpg"
map_src = Image.open(source_map).convert('RGBA')
source_W, source_H = map_src.size
out_image = Image.new(mode="RGBA", size=(source_W, source_H)) # create blank output image
pixel_access_object_src = map_src.load()
pixel_access_object_out = out_image.load()
#####################################################################################
# THIS WORKS, BUT IT SHOULDN'T.. I AM DIVIDING BY ZERO ( source_H/line_Y )
#####################################################################################
for line_Y in range(0, source_H, 1):
print(f"line_Y: {line_Y}")
ratio_1 = line_Y/source_H * source_W
ratio_2 = int((1 - (line_Y/source_H))/2 * source_W)
# ratio_3 = int(source_H/(line_Y)) # IT FAILS HERE BUT NOT BELOW. WHY?
for dot_X in range(0, int(ratio_1), 1):
pixel_access_object_out[ int(dot_X + ratio_2) , line_Y ] = \
pixel_access_object_src[ int(dot_X * source_H/line_Y ) , line_Y ] # THIS SHOULDN'T WORK; line_Y=0; div by zero
#####################################################################################
out_image.show(); out_image.save("triangle.png"); out_image.close() ```
[![No divide by zero error][1]][1]
[1]: https://i.sstatic.net/X6lAR.png
If line_y
is 0, then ratio_1
will be 0, which means the inner for dot_X in range(0, int(ratio_1), 1):
will never be entered since range(0, 0)
results in a 0-length iterable. Because that loop is never entered, the potentially error-producing code within it is never run.