在进行 Mandelbrot 迭代绑定/非绑定测试器时,在 Python 3 中使用 while 循环后,您可以引用原始变量值吗?

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

我正在制作一个Python 3程序,它告诉你输入一个有理数,将该数字转换为浮点数,将其传递给实际迭代的while循环,然后通知用户它是绑定还是未绑定(基本上看到如果程序适合 Mandelbrot 集)。我的问题在于最后一部分。我试图让它检查 while 循环运行的值是否大于原始值,如果是,则会打印它是未绑定的。反之亦然也会发生同样的情况。 (我试图在 if/else 中完成这一切)但是我如何引用该原始值?

print('The best Mandelbrot iteration from Python!')
print('Please enter any rational you would like to check if it belongs to the Mandelbrot set.')
z = 0
c = input()
cc = c.replace(',', '.')
ccc = float(cc)
n = 0
while z < 1000 and n < 15 :
    print( str(z) + (', ') + (   'Count: ' + str(n)  ) )
    z = z**2 + ccc
    n = n + 1

我尝试根据它的迭代次数使其打印绑定/未绑定。该程序原本如果未绑定的话将永远持续下去。我的意思是这个(n是计数器):

if n >= 3:
    print('Unbound!')
elif n < 3:
    print('Bound!')
    
python python-3.x while-loop mandelbrot
1个回答
0
投票

如果您只想更改最后的打印,您可以使用 f 字符串。

if n >= 3:
    print(f'{c} is unbound!')
elif n < 3:
    print(f'{c} is bound!')

将输入输入到变量

c
并将浮点数放入
ccc
中的更简洁方法是
ccc = float((c:=input()).replace(",","."))

我遇到了您的代码无法正常工作的问题。我在这个site上发现了一个小函数,它可以工作并返回一个布尔结果,该值是稳定的,因此在Mandelbrot集中。

def is_stable(c, num_iterations):
    z = 0
    for _ in range(num_iterations):
         z = z ** 2 + c
    return abs(z) <= 2

希望这对您有帮助。

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