以下是我的代码段,用于通过NumPy
,SciPy
和MatPlotLib
库绘制整数函数:
import numpy as np
from scipy.integrate import quad
import matplotlib.pyplot as plt
sigma = 1
def integrand(x,n):
return (n/(2*sigma*np.sqrt(np.pi)))*np.exp(-(n**2*x**2)/(4*sigma**2))
tt = np.linspace(0, 20, 0.01)
nn = np.linspace(1, 100, 1)
T = np.zeros_like([len(tt), len(nn)])
for i,t in enumerate(tt):
for j,n in enumerate(nn):
T[i,j] = quad(integrand, -oo, t, args = (x))
plt.pcolormesh(tt,nn,T)
但是ValueError
与unpacking
相关的问题如下:
Traceback (most recent call last):
File "C:\Program Files\Microsoft Visual Studio 12.0\Common7\IDE\Extensions\Microsoft\Python Tools for Visual Studio\2.1\visualstudio_py_util.py", line 106, in exec_file exec_code(code, file, global_variables)
File "C:\Program Files\Microsoft Visual Studio 12.0\Common7\IDE\Extensions\Microsoft\Python Tools for Visual Studio\2.1\visualstudio_py_util.py", line 82, in exec_code exec(code_obj, global_variables)
File "C:\Users\Matinking\documents\visual studio 2013\Projects\NeuroSimulation\NeuroSimulation\XSundry\test2.py", line 63, in <module>
plt.pcolormesh(tt,nn,T)
File "C:\Python34\lib\site-packages\matplotlib\pyplot.py", line 2946, in pcolormesh
ret = ax.pcolormesh(*args, **kwargs)
File "C:\Python34\lib\site-packages\matplotlib\axes.py", line 7747, in pcolormesh
X, Y, C = self._pcolorargs('pcolormesh', *args, allmatch=allmatch)
File "C:\Python34\lib\site-packages\matplotlib\axes.py", line 7357, in _pcolorargs
numRows, numCols = C.shape
ValueError: need more than 1 value to unpack
Press any key to continue . . .
该问题似乎与代码的最后一行有关,但我无法找到任何解决方案......
你能不能在这个案子上启发我?
亲切的问候
答案 0 :(得分:2)
import numpy as np
from scipy.integrate import quad
import matplotlib.pyplot as plt
sigma = 1
def integrand(x, n):
return (n/(2*sigma*np.sqrt(np.pi)))*np.exp(-(n**2*x**2)/(4*sigma**2))
tt = np.linspace(0, 19, 20) # divides range 0 to 19 into 20 equal size portions. Thus, tt = [0, 1, 2, ..., 19]
nn = np.linspace(1, 100, 100) # nn = [1, 2, ..., 100]
T = np.zeros([len(tt), len(nn)])
for i,t in enumerate(tt):
for j,n in enumerate(nn):
T[i, j], _ = quad(integrand, -np.inf, t, args=(n,)) # evaluate integral from -infinity to t, with value of n in the function set to n passed in from here.
x, y = np.mgrid[0:20:1, 1:101:1] # create a mesh/grid for plotting.
plt.pcolormesh(x, y, T) #plot
plt.show()