为什么“除以零”有时在 python3 中有效?

问题描述 投票:0回答:1

我编写了一个Python脚本,可以将图像从矩形逐渐缩放为三角形。有用。不应该。我发现在 for 循环中,索引从零开始,并用作像素位置函数中的分母。当我尝试在循环外声明变量时,我发现了这种奇怪的行为。 为什么它有效?我数学坏了吗?我发现了无限吗?我的诺贝尔奖在哪里?

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.stack.imgur.com/X6lAR.png
python-3.x divide-by-zero
1个回答
1
投票

如果

line_y
为 0,则
ratio_1
将为 0,这意味着内部
for dot_X in range(0, int(ratio_1), 1):
永远不会被输入,因为
range(0, 0)
会导致 0 长度的可迭代。由于永远不会进入该循环,因此永远不会运行其中可能产生错误的代码。

© www.soinside.com 2019 - 2024. All rights reserved.