首页 > 解决方案 > 复数中的 Mandelbrot 集绘图和 ZeroDivisionError

问题描述

我正在制作一个绘制 Mandelbrot Set 版本的代码。当它运行时,它接受两个输入,a 和 b,并将其转换为复数(例如 complex(a,b)。)然后它绘制一个 Mandelbrot 集,其中 z 是复数的幂,加上 c,与 z**2+c 的普通版本不同。但是复数的某些输入,例如 5 和 6,有时会给出错误 ZeroDivisionError: complex 除以零,或者有时,它不会给出任何输出。有时,当我输入 1 和 1 时,它会起作用,并输出如下所示:

这是我关于 stackoverflow 的第一个问题,所以我不确定那张图片是否有效,但无论如何,它看起来不像普通的 Mandelbrot 集。怎么了?另外,这是我的代码:

import turtle
s=turtle.Screen()
t=turtle.Turtle()
a=int(input())
b=int(input())
h=complex(a,b)
t.pu()
t.goto(-200, 200)
turtle.tracer(0,0)
t.speed(0)
for y in range(200,-200,-1):
  turtle.update()
  for x in range(-250,200):
    t.goto(x,y)
    r=float(float(x)/170)
    i=float(float(y)/170)
    c=complex(float(r),float(i))
    z=complex(0,1)
    for exptest in range(50):
      z=(z**h)+c
      if abs(z)>2:
        if exptest>0:
          t.color('black')
          if exptest>1:
            t.color('yellow')
            if exptest>2:
              t.color('green')
              if exptest>3:
                t.color('red')
                if exptest>5: 
                  t.color('orange')
                  if exptest>10:
                    t.color('purple')
                    if exptest>20:
                      t.color('blue')
                      if exptest>30:
                        t.color('light blue')
        else:
          t.color('light green')
        t.dot(1)
        break

标签: python

解决方案


对于复数,求幂没有明确定义。您可以定义a ** bax exp(log(a) * b),但log(a)最多只能定义2pi i,因此您有无限种可能性。对于整数幂,您可以定义z**kz * z * ... *z k时间,但这几乎可以肯定不是python 所做的k定义,complex就像您在上面所做的那样。


推荐阅读