您能否修复此错误“只能将size1数组转换为Python标量”

2024-04-25 15:03:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我想画gamma函数,这是我的脚本

from math import *
import matplotlib.pyplot as plt
from scipy.integrate import quad
import numpy as np 

def f(x,n):
    result = (x**(n-1))*(exp(-x))
    return result 

def gamma(n):
    r1 = quad(f, 0, np.inf, args=n)
    r2 = np.array(r1)
    r3 = r2[0]
    return round(r3,2)

n = np.arange(1,10, step=0.1)
plt.plot(n, gamma(n))
plt.show()

但我犯了这个错误

File "/home/yassir/python/desktop/plot_gamma.py", line 17, in <module>
plt.plot(n, gamma(n))
File "/home/yassir/python/desktop/plot_gamma.py", line 11, in gamma
r1 = quad(f, 0, np.inf, args=n)
File "/usr/lib/python3/dist-packages/scipy/integrate/quadpack.py", line 341, in quad
retval = _quad(func, a, b, args, full_output, epsabs, epsrel, limit,
File "/usr/lib/python3/dist-packages/scipy/integrate/quadpack.py", line 455, in _quad
return _quadpack._qagie(func,bound,infbounds,args,full_output,epsabs,epsrel,limit)
TypeError: only size-1 arrays can be converted to Python scalars

1条回答
网友
1楼 · 发布于 2024-04-25 15:03:16

您不必自己计算,您可以直接从scipyscipy.special.gamma使用它。例如:

import numpy as np
import matplotlib.pyplot as plt
from scipy.special import gamma

x = np.arange(1,10, step=0.1)
y = gamma(x)
plt.plot(x, y)

gamma_example

相关问题 更多 >