[python高效能程式設計-學習筆記]章節2.3計算完整的Julia集合
阿新 • • 發佈:2019-02-04
Python高效能程式設計2014版中2.3採用了Julia集合作為範例來作為效能分析的範例,下面是作為一個python初階使用者在學習示例中遇到的一些問題,我在這裡把他們記錄下來,作為備忘。同時希望能夠幫助到後續學習該書的同學解決一些疑點。
首先是對Julia集合的介紹。以下關於Julia集合的定義摘自百度百科。
圖1-Julia集合的定義
本章需要做的事情是採用程式碼去生成這個集合,並且在其中加上對於程式碼的部分效能分析,程式碼不展示ru生成圖形的部分。下面
是生成Julia集合的程式碼。
def calc_pure_python(desired_width, max_iterations): """Create a list of complex coordinates (zs) and complex parameters (cs), build Julia set, and display""" x_step = (float(x2 - x1) / float(desired_width)) y_step = (float(y1 - y2) / float(desired_width)) x = [] y = [] ycoord = y2 while ycoord > y1: y.append(ycoord) ycoord += y_step xcoord = x1 while xcoord < x2: x.append(xcoord) xcoord += x_step # Build a list of coordinates and the initial condition for each cell. # Note that our initial condition is a constant and could easily be removed; # we use it to simulate a real-world scenario with several inputs to # our function. zs = [] cs = [] for ycoord in y: for xcoord in x: zs.append(complex(xcoord, ycoord)) cs.append(complex(c_real, c_imag)) print "Length of x:", len(x) print "Total elements:", len(zs) start_time = time.time() output = calculate_z_serial_purepython(max_iterations, zs, cs) end_time = time.time() secs = end_time - start_time print calculate_z_serial_purepython.func_name + " took", secs, "seconds" # This sum is expected for a 1000^2 grid with 300 iterations. # It catches minor errors we might introduce when we're # working on a fixed set of inputs. assert sum(output) == 33219980
作為一個初階python使用者,我在閱讀這段程式碼的時候,碰到的問題有如下兩個。
第一個問題,函式呼叫了一個名為complex()的函式,該函式是python標準內建函式庫中的一個函式,這個函式的作用是生成複數。
具體的使用方法如下:
示例:
#complex()
print(complex(1))
print(complex('2+1j'))
print(complex(2, 5))
l = [1, 3, 4, 5]
for i in l:
print(complex(i, 5))
結果:
當直接使用complex(n)時,會返回一個(n+0j)的複數,預設虛部為0。(1+0j) (2+1j) (2+5j) (1+5j) (3+5j) (4+5j) (5+5j)
而當指定了虛部時,例如呼叫complex(x,j),則會返回一個形如(x+yj)的複數。
需要注意的是,complex還可以通過complex('2+1j')這種形式直接生成一個形如(2+1j)的複數。
第二個問題出現在一個自定義的函式calculate_z_serial_purepython中,這個函式程式碼如下。
def calculate_z_serial_purepython(maxiter, zs, cs): """Calculate output list using Julia update rule""" output = [0] * len(zs) for i in range(len(zs)): n = 0 z = zs[i] c = cs[i] while abs(z) < 2 and n < maxiter: z = z * z + c n += 1 output[i] = n return output
這個函式中有一個針對列表output的初始化定義,使用的是[0]*len(zs),這是為了將list初始化為長度為zs的長度,元素全部為0的一種標準賦值方法。
引用:
1High Performance Python byMicha Gorelick and Ian Ozvald(O'Rilly).Copyright 2014 Micha Gorelick and Ian Ozsvald,
978-1-449-36159-4