当前位置: 首页 > 知识库问答 >
问题:

我试图创建一个GIF缩放到Python中的Mandelbrot集,但在浮点数方面遇到了一些麻烦

相德宇
2023-03-14
from PIL import Image
import numpy as np
import math

class Fractal(object):

    def __init__(self, resolution=(720,720), x_range=(-2.0,2.0), y_range=(-2.0,2.0), maxIterations=255, zoom=0, zoomRate=0):
        self.resolution = resolution
        self.x_range = x_range
        self.y_range = y_range
        self.maxIterations = maxIterations
        self.zoom = zoom
        self.zoomRate = zoomRate

    def computePixel(self, x, y):
        z = complex(0.0,0.0)
        c = complex(x,y)
        iterations = 0
        while iterations < self.maxIterations or abs(z)<2:
            z = z*z + c
            iterations += 1
        # pixelHue = (360/self.maxIterations)*iterations
        # RGB = hsv_to_rgb(pixelHue, 0.0, 0.0)
        # return RGB
        return iterations

    def generateFrame(self):
        #x_max, x_min, y_max, y_min = self.zoom()
        x_max, x_min, y_max, y_min = (self.x_range[1],self.x_range[0],self.y_range[1],self.y_range[0])
        x_increment = (x_max - x_min)/self.resolution[0]
        print(x_increment)
        y_increment = (y_max - y_min)/self.resolution[1]
        print(y_increment)
        frame = []
        yPixels = []
        for x in np.arange(x_min, x_max, x_increment):
            for y in np.arange(y_min, y_max, y_increment):
                x,y = float(x), float(y)
                iterations = self.computePixel(x,y)
                print(x,y,iterations)
        #         pixel_RGB= self.computePixel(x,y)
        #         yPixels.append(pixel_RGB)
        #     frame.append(yPixels)
        # return frame


    def zoom(self):
        '''this is the change that will happen in one second'''
        x_max = self.x_range[1]-(self.zoomRate/2)
        x_min = self.x_range[0]+(self.zoomRate/2)
        y_max = self.y_range[1]-(self.zoomRate/2)
        y_min = self.y_range[0]+(self.zoomRate/2)
        return (x_max, x_min, y_max, y_min)

    def sweep(self):
        for x in np.arange(self.size[0]):
            for y in np.arange(self.size[1]):
                pass



def hsv_to_rgb(h, s, v):
    if s == 0.0: return (v, v, v)
    i = int(h*6.) # XXX assume int() truncates!
    f = (h*6.)-i; p,q,t = v*(1.-s), v*(1.-s*f), v*(1.-s*(1.-f)); i%=6
    if i == 0: return (v, t, p)
    if i == 1: return (q, v, p)
    if i == 2: return (p, v, t)
    if i == 3: return (p, q, v)
    if i == 4: return (t, p, v)
    if i == 5: return (v, p, q)

f = Fractal()
f.generateFrame()     

目前,我只想显示GIF的第一帧,即未放大的Mandelbrot集。但是,当我尝试迭代所有像素值时,迭代停止在x=-1.8611111111116y=-0.0055562641

我猜这是因为当y应该为零时发生了一些溢出错误,但我不知道如何解决这个问题。

这是命令行的最后一个屏幕截图,在这里我打印了所有复数的实部和虚部,以及该数字收敛所需的迭代次数(如果输出为255,则不需要)。

共有1个答案

施德运
2023-03-14

您需要将while循环条件更改为:

while iterations < self.maxIterations and abs(z)<2:

否则,循环将运行很长时间,因为abs(z)小于2。

 类似资料: