gpt4 book ai didi

Python 多处理 pylab 傅里叶

转载 作者:行者123 更新时间:2023-12-01 05:42:39 25 4
gpt4 key购买 nike

我正在尝试绘制方波的傅立叶序列,但是对于许多项,该程序需要太多时间来计算所有点。我尝试使用多处理模块但没有成功。请帮助我如何使用多处理。我正在 fedora linux 上运行,并拥有 AMD FX Octa 核心。谢谢

#!/usr/bin/env python

import pylab,math

#Square Wave approximation by Fourier Series:
#y=4/pi*(sin(x) + sin(3x)/3 + sin(5x)/5 + ... n) terms

n=input("how many terms do you want?")
y=[]
# generate x's to calculate the points.
x=pylab.arange(0,360,0.5)
#generate de odd numbers to add the sines terms
impar=range(1,n+2,2)
no=4/math.pi #just for normalize the sequence to converge to 1 (not pi/4)
#calculate the points
for ps in x:
a=0
for i in impar:
a=a+(((math.sin(math.radians(i*ps)))/i))
a=no*a
y.append(a)

#plot
pylab.figure()
pylab.plot(x,y,"o")
pylab.title(str(n)+str(" terms"))
pylab.grid()
#save a image(just in case)
pylab.savefig(str(n)+str("sqwv.png"))
#show the graph
pylab.show()

最佳答案

这个问题是并行的,所以很容易让脚本使用多个CPU。建立在 @HYRY's answer 之上:

from multiprocessing.dummy import Pool # use threads

def compute_y(i):
np.add.reduce(no * np.sin(np.radians(impar * x[i])) / impar, out=y[i])

step = 10**8 // n
Pool().map(compute_y, (slice(j, j + step) for j in range(0, len(x), step)))

矢量化 numpy 操作释放了 GIL,因此该代码应该能够利用多个 CPU。

完整脚本:

#!/usr/bin/env python
"""Square Wave approximation by Fourier Series."""
import math
from multiprocessing.dummy import Pool # use threads
from timeit import default_timer as timer

import matplotlib.pyplot as plt
import numpy as np

n = 100000 # compute first n terms in the series

# generate x's to calculate the points.
x = np.arange(0, 360, .1)

# generate odd numbers to add the sines terms
impar = np.c_[1:n+2:2]
no = 4 / math.pi # just for normalize the sequence to converge to 1 (not pi/4)

# calculate the points
start = timer()
# y = 4/pi*(sin(x) + sin(3x)/3 + sin(5x)/5 + ... n) terms
y = np.empty_like(x)

def compute_y(i):
t = impar * x[i]
np.radians(t, out=t)
np.sin(t, out=t)
t *= no
t /= impar
np.add.reduce(t, out=y[i])

step = 10**8 // n
Pool().map(compute_y, (slice(j, j + step) for j in range(0, len(x), step)))
print("y calc. takes us %.2f seconds" % (timer() - start,))

# plot
plt.plot(x, y, "-")
plt.title("%d terms" % n)
plt.grid()
# save a image(just in case)
plt.savefig("%dsqwv.png" % n)
# show the graph
plt.show()

关于Python 多处理 pylab 傅里叶,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17139222/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com