2017-08-12 22 views
1

私のマンデルブロプログラムで画像を書き込めません。これは "(maxy-miny)/ width"ライン31と比較して "(maxx-minx)/ width"の丸め誤差を伴い、500平方の画像ではなく501×500の画像になります。 ((width + 1)* length)ではありません(width * length)。 これを修正するにはどうすればよいですか?PILの丸め誤差

from PIL import Image 
from cmath import * 
from math import sqrt 
from numpy import arange 

width = 500 
height = 500 

minx = -0.752 #float(input("Please enter the minimum x value:")) 
maxx = -0.748 #float(input("Please enter the maximum x value:")) 
miny = 0.098 #float(input("Please enter the minimum y value:")) 
maxy = 0.102 #float(input("Please enter the maximum y value:")) 

gradient = Image.open("mandelbrot.png") 
gradlist = list(gradient.getdata()) 

def testMandelbrot(x, y): 
    z = 0 + 0j 
    c = x + (y*1j) 
    iter = 0 
    while iter <= 69 and sqrt(z.real**2 + z.imag**2) < 4: 
     z = (z*z) + c 
     iter += 1 
    if iter == 70: 
     return (0, 0, 0, 255) 
    else: 
     return gradlist[int((iter - 1) * 140/70)] 

img = Image.new('RGBA', (width, height), color=(255, 255, 255, 255)) 
image = [testMandelbrot(x, y) for y in arange(miny, maxy, (maxy-miny)/height) for x in arange(minx, maxx, (maxx-minx)/width)] #this line creates the error ((maxx-minx)/width)/(maxx - min) gives (width+1) not width 
print(len(image), img.size) 
img.putdata(image) 
img.save("picture111.png", "PNG") 
+0

私は強制的に値を丸めようとしましたが、丸め誤差が悪化しています。私は何をすべきか? –

答えて

2

私はarangeではなくnumpy's linspaceを使用してお勧めしたいです。指定された数のサンプルが均等に配置された配列を返します。

linspace(0.098, 0.102, 500, endpoint=False)は、正確に500ポイントの長さです。エンドポイントを含める場合は、endpoint=Falseを省略するか、endpoint=Trueを渡すことができます。

endpoint=False同じサイズの高さと幅の同じ画像を生成して、その差がmax_ - min_の間にある場合、その結果は隣接するタイルになります。

あなたのコードは次のようになります。

Y = linspace(miny, maxy, height, endpoint=False) 
X = linspace(minx, maxx, width, endpoint=False) 
image = [testMandelbrot(x, y) for y in Y for x in X] 

Ylen(X)度も再利用され、高さと幅は、(500)小型であるため、それは多くのエイズ可読性はかかりませんので、私は配列に名前を付けます。

+0

ありがとうございます - これで私の問題は解決しました。 –