如何在python中使用1个函数并行化2 for循环

时间:2013-03-16 10:51:37

标签: python parallel-processing

您好我的代码如下:

import numpy as np
from scipy import pi,sin,cos
import matplotlib.pyplot as plt
import math as m

image = np.zeros(shape=(201,201))

a=4
b=3
pa = 45

def dE(i,j,a,b,PA,x0,y0):
    the = -PA+90.0
    x=i - x0
    y=j - y0
    cos_a,sin_a=cos(the*pi/180.0),sin(the*pi/180.0)
    Xs = (x*cos_a - y*sin_a)**2.0 
    Ys = (x*sin_a + y*cos_a)**2.0 
    r = np.sqrt((Xs/a**2) + (Ys/b**2)) 
    return r

for i in range(0,len(image)):
    for j in range(0,len(image)):
        image[j,i] = dE(i,j,a,b,pa,100.0,100.0)

plt.imshow(image)
plt.show()

如何将底部的两个for循环并行化?提前谢谢!

我已添加上面的完整代码。干杯克里斯

1 个答案:

答案 0 :(得分:0)

好的,谢谢你的意见真有帮助!

import numpy as np
from scipy import pi,sin,cos
import matplotlib.pyplot as plt
import math as m

image = np.zeros(shape=(201,201))

a=4
b=3
pa = 240

def dEllipse(x,y,a,b,PA):
    the = -PA+90.0
    cos_a,sin_a=cos(the*pi/180.0),sin(the*pi/180.0)
    Xs = (x*cos_a - y*sin_a)**2.0 
    Ys = (x*sin_a + y*cos_a)**2.0 
    r = np.sqrt((Xs/a**2) + (Ys/b**2)) 
    return r

x = np.arange(0-100.0, 201-100.0)
y = np.arange(0-100.0, 201-100.0)
xx, yy = np.meshgrid(x, y)

new_image= dEllipse(xx,yy,a,b,pa)

plt.imshow(new_image)
plt.show()