0

大家好,我做了这个函数,它给出了 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”

反正有没有让这个启动和运行?

4

1 回答 1

0

对于任意函数传递问题->

我发现自己通过创建正在传递的函数的深层副本来解决 99% 的问题。

请参阅这篇文章以制作函数深拷贝: 如何在 Python 中制作函数的深拷贝?

如果内存不是瓶颈,并且您只想让某些东西正常工作,那么可能值得一试。

import types
def copy_func(f, name=None):
    return types.FunctionType(f.func_code, f.func_globals, name or f.func_name,
        f.func_defaults, f.func_closure)

所以现在你可以试试:

for i in range(nprocs):

    workercopy = copy_func(worker)

    p = mp.Process(
            target = workercopy,
            args=(x, chunksize * i, chunksize, out_q,)
            )
    procs.append(p)
    p.start()
于 2015-11-12T21:50:49.010 回答