我正在尝试计算两点角度相关函数的统计S_1/2。我的代码是:
# Importing libraries
from scipy.integrate import quad
from math import radians
# Converting the degrees into radians
theta_rad=np.radians(theta)
# I define a integrand function
def integrand(theta, C_theta):
cos_theta = np.cos(theta)
return -C_theta**2 * np.sin(theta)
def compute_statistic(theta_rad, C_theta):
integrand_values = lambda theta: integrand(theta, C_theta)
integral, error = quad(integrand_values, 0, np.pi) # Adjusted integration limits
return integral, error
s_half = compute_statistic(theta_rad, C_theta)
print("The value of S_1/2 is:", s_half)
这给了我一个以下错误:
只有 size-1 数组可以转换为 Python 标量
在我看来 integrand_values 是一个 np.ndarray 并且四元函数必须有一个函数。
祝你有美好的一天!
我一直在尝试将 integrand_values 更改为一个函数,它给我一个浮点数。
使用你的函数,如果我给出
compute_statistic
两个数字,我会得到一个结果
In [4]: compute_statistic(0,0)
Out[4]: (0.0, 0.0)
如果我将第二个作为数组,我会收到错误:
In [5]: compute_statistic(0,np.arange(3))
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Cell In[5], line 1
----> 1 compute_statistic(0,np.arange(3))
Cell In[3], line 7, in compute_statistic(theta_rad, C_theta)
5 def compute_statistic(theta_rad, C_theta):
6 integrand_values = lambda theta: integrand(theta, C_theta)
----> 7 integral, error = quad(integrand_values, 0, np.pi) # Adjusted integration limits
8 return integral, error
File ~\miniconda3\lib\site-packages\scipy\integrate\_quadpack_py.py:463, in quad(func, a, b, args, full_output, epsabs, epsrel, limit, points, weight, wvar, wopts, maxp1, limlst, complex_func)
460 return retval
462 if weight is None:
--> 463 retval = _quad(func, a, b, args, full_output, epsabs, epsrel, limit,
464 points)
465 else:
466 if points is not None:
File ~\miniconda3\lib\site-packages\scipy\integrate\_quadpack_py.py:575, in _quad(func, a, b, args, full_output, epsabs, epsrel, limit, points)
573 if points is None:
574 if infbounds == 0:
--> 575 return _quadpack._qagse(func,a,b,args,full_output,epsabs,epsrel,limit)
576 else:
577 return _quadpack._qagie(func,bound,infbounds,args,full_output,epsabs,epsrel,limit)
TypeError: only size-1 arrays can be converted to Python scalars
好吧,错误并不像我希望的那么清楚,可能是因为
_qagie
,是一个编译函数。因此,让我们猜测一下,看看 func
通过此输入返回到哪里。
In [6]: integrand(0,np.arange(3))
Out[6]: array([ 0., -0., -0.])
使用数组
C_theta
,该函数返回一个数组。 quad
不喜欢这样!
使用标量值,我们得到标量结果,并且
quad
运行良好:
In [8]: integrand(10, 3)
Out[8]: 4.896189998004328
In [9]: compute_statistic(10,3)
Out[9]: (-18.0, 1.9984014443252818e-13)
第一个参数
rad_theta
没有用。在 integrand
中,您计算 cos
,但不使用它。但你确实使用了C_theta
。