Python错误:无法将复数转换为浮点数

时间:2018-12-13 09:49:55

标签: python

from scipy.integrate import quad

def integrand(y,a):

    x = ((1-((0.0001303290910*y**2)/0.9520444748+a*y))*(1/0.0002017404542))**(0.5)

    return float(x)

a = 0.005

volume = quad(integrand,-70,110,args=(a))

print(volume)

无论我做什么,我都会遇到相同的错误,而且似乎找不到问题。

Here is my error

TypeError                                 Traceback (most recent call last) <ipython-input-23-42d96b8cb524> in <module>()
      9 a = 0.005
     10 
---> 11 volume = quad(integrand,-70,110,args=(a))
     12 
     13 print(volume)


~/anaconda3/lib/python3.6/site-packages/scipy/integrate/quadpack.py in quad(func, a, b, args, full_output, epsabs, epsrel, limit, points, weight, wvar, wopts, maxp1, limlst)
    339     if weight is None:
    340         retval = _quad(func, a, b, args, full_output, epsabs, epsrel, limit,
--> 341                        points)
    342     else:
    343         retval = _quad_weight(func, a, b, args, full_output, epsabs, epsrel,

~/anaconda3/lib/python3.6/site-packages/scipy/integrate/quadpack.py in
_quad(func, a, b, args, full_output, epsabs, epsrel, limit, points)
    446     if points is None:
    447         if infbounds == 0:
--> 448             return _quadpack._qagse(func,a,b,args,full_output,epsabs,epsrel,limit)
    449         else:
    450             return _quadpack._qagie(func,bound,infbounds,args,full_output,epsabs,epsrel,limit)

TypeError: can't convert complex to float

1 个答案:

答案 0 :(得分:0)

实际上,这是数学问题,而不是Python。您正在尝试计算潜在负数的平方根。如果a ** b为正,则Python的float返回一个a,如果为负,则返回一个complex数字:

In [28]: (-1) ** 0.5
Out[28]: (6.123233995736766e-17+1j)

复数不能轻易转换为浮点数,这就是您看到的错误。

如果不知道确切的应用程序,就很难提出解决方案。如果所有值均应为正,则您的公式中可能存在错误。如果不是,那么您必须重新考虑您尝试做的在数学上是否正确。

有帮助吗?