这是我尝试使用Pygame模块在python3.5中编程Mandelbrot集。在
import math, pygame
pygame.init()
def mapMandelbrot(c,r,dim,xRange,yRange):
x = (dim-c)/dim
y = (dim-r)/dim
#print([x,y])
x = x*(xRange[1]-xRange[0])
y = y*(yRange[1]-yRange[0])
x = xRange[0] + x
y = yRange[0] + y
return [x,y]
def checkDrawBox(surface):
for i in pygame.event.get():
if i.type == pygame.QUIT:
pygame.quit()
elif i.type == pygame.MOUSEBUTTONDOWN:
startXY = pygame.mouse.get_pos()
boxExit = False
while boxExit == False:
for event in pygame.event.get():
if event.type == pygame.MOUSEBUTTONUP:
boxExit = True
if boxExit == True:
return [startXY,pygame.mouse.get_pos()]
pygame.draw.rect(surface,[255,0,0],[startXY,[pygame.mouse.get_pos()[0]-startXY[0],pygame.mouse.get_pos()[1]-startXY[1]]],1)
pygame.display.update()
def setup():
dimensions = 500
white = [255,255,255]
black = [0,0,0]
checkIterations = 100
canvas = pygame.display.set_mode([dimensions,dimensions])
canvas.fill(black)
xRange = [-2,2]
yRange = [-2,2]
xRangePrev = [0,0]
yRangePrev = [0,0]
newxRange = [0,0]
newyRange = [0,0]
while True:
if not ([xRange,yRange] == [xRangePrev,yRangePrev]):
draw(dimensions, canvas, xRange, yRange, checkIterations)
pygame.display.update()
xRangePrev = xRange
yRangePrev = yRange
box = checkDrawBox(canvas)
if box != None:
maxX = max([box[0][0],box[1][0]])
maxY = max([box[0][1],box[1][1]])
newxRange[0] = mapMandelbrot(box[0][0],0,dimensions,xRange,yRange)[0]
newxRange[1] = mapMandelbrot(box[1][0],0,dimensions,xRange,yRange)[0]
newyRange[0] = mapMandelbrot(0,box[0][1],dimensions,xRange,yRange)[1]
newyRange[1] = mapMandelbrot(0,box[1][1],dimensions,xRange,yRange)[1]
xRange = newxRange
yRange = newyRange
def draw(dim, surface, xRange, yRange, checkIterations):
for column in range(dim):
for row in range(dim):
greyVal = iteration(0,0,mapMandelbrot(column,row,dim,xRange,yRange),checkIterations,checkIterations)
surface.set_at([dim-column,row],greyVal)
def iteration(a, b, c, iterCount, maxIter):
a = (a*a) - (b*b) + c[0]
b = (2*a*b) + c[1]
iterCount = iterCount - 1
if iterCount == 0:
return [0,0,0]
elif abs(a+b) > 17:
b = (iterCount/maxIter)*255
return [b,b,b]
else:
return iteration(a,b,c,iterCount,maxIter)
setup()
我相信迭代算法是正确的,但是输出看起来不正确:
想知道是什么问题吗?抱歉,代码转储,只是不确定哪个部分可能导致它看起来像那样。在
迷人的虫子它看起来像一只被压扁的虫子:)
问题在于两条线:
您正在更改第一行中
a
的含义,因此在第二行中使用了错误的a
。在解决方法很简单:
^{pr2}$这将导致在计算右手边时使用相同的
a
值。在弄清楚你的bug到底产生了什么是很有趣的。尽管它不是曼德尔布洛特集,但它本身似乎是一个有趣的分形。从这个意义上说,你有一个非常幸运的虫子。99%的情况下,bug会导致垃圾,但它们时不时会产生一些有趣的东西,但只是无意中的。在
编辑时:
Mandelbrot集合基于复多项式的迭代:
这个bug产生的伪Mandelbrot集是基于迭代函数的
其中}是提取复数实部和虚部的运算符。这不是}是{}的复共轭)。由于这是一个相当自然的错误,几乎可以肯定的是,这已经出现在曼德尔布洛特集的文献中,尽管我不记得见过它。在
Re()
和{z
中的多项式,尽管很容易看出它是z,z*
(其中{我决定学习曼德尔布洛特集,并写了我自己的版本!我使用了python的
complex
数据类型,这将使每个像素的mandelbrot计算更加清晰。以下是结果截图:下面是源代码/代码转储:
这段代码的两个问题是:第一,更新mandelbrot集的速度非常慢;第二,如果使用非方形窗口或框选择,纵横比会失真。如果有任何代码不清楚,请告诉我!在
相关问题 更多 >
编程相关推荐