大家好,我做了这个函数,它给出了 arctan 的泰勒展开的前 n 项的总和:我正在使用 mpmath 模块,mpf 是任意精度浮点类型。
def atantaylor(x,n):
#Taylor series expansion of arctan about 0 for n terms, evaluated at x
sum = 0
xt = x
xsq = x**2
for j in range(n):
nterm = ((-1)**j * xt) /(2.0*j+1)
xt = xt * xsq
sum += nterm
return sum
我想让它在几个内核上运行,所以我创建了另一个函数,从术语 n 到 n+cs 总和,理想情况下,我可以并行运行其中一些以使其更快:
def taylor1(x,n,cs):
#Sum of Taylor series of atan from n to n + cs - 1
sum = mpf(0)
#Find term n
xt = mpf(x **(2*n + 1))
xsq = mpf(x**2)
#Loop from n to n + cs - 1
for j in range(n, n+cs):
nterm = ((-1)**j * xt) /(2.0*j+1)
xt = xt * xsq
sum += nterm
print "term %d is %r" % (j, nterm)
print sum
return sum
这里的想法是我可以运行一些间隔为 [0, cs] [cs, cs*2] [cs*2, cs*3] 的进程。
我对多处理很陌生,我在本教程中模仿了以下代码
def mp_atan(x, n, nprocs):
#nprocs must be a factor of n so each worker can receive the same number of tasks that are integer value
if n % nprocs != 0:
print "please give an n that is a multiple of nprocs"
return 0
def worker(x, n, chunksize, out_q):
a = tan_n(x, n, chunksize)
out_q.put([a])
out_q = mp.Queue()
chunksize = int(n / nprocs)
procs = []
for i in range(nprocs):
p = mp.Process(
target = worker,
args=(x, chunksize * i, chunksize, out_q,)
)
procs.append(p)
p.start()
#sum results
sum = 0
for i in range(nprocs):
sum += out_q.get()
#wait for all workers to finish
for p in procs:
p.join()
return sum
我收到 EOFError 和“pickle.PicklingError: Can't pickle : it's not found as mc.worker”
反正有没有让这个启动和运行?