【问题标题】:TypeError: can't convert expression to float - definite integral sympyTypeError:无法将表达式转换为浮点数 - 定积分 sympy
【发布时间】:2020-05-20 04:51:06
【问题描述】:
import math

import scipy.integrate

import sympy

m1 = sympy.Symbol('m1')

m2 = sympy.Symbol('m2')

s = sympy.Symbol('s')

T = sympy.Symbol('T')

k = sympy.Symbol('k')

integral = sympy.integrate(((k**2)/8 * math.pi)*(1/(math.sqrt(k**2 + m1**2) * math.sqrt(k**2 + m2**2)))*(1/(math.sqrt(s)-math.sqrt(k**2 + m1**2)-math.sqrt(k**2 + m2**2)))
                         * ((1/(math.exp((math.sqrt(k**2 + m1**2))/T)-1))+(1/(math.exp((math.sqrt(k**2 + m2**2))/T)-1))), (k, 10**-15, math.inf))
print(integral)

【问题讨论】:

  • 使用 sympy.sqrt 和 sympy.pi 而不是 math.sqrt 和 math.pi。

标签: python typeerror sympy integrate


【解决方案1】:

为了说明`@Oscar 的评论

In [28]: math.sqrt(s)                                                                    
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-28-443c32f84854> in <module>
----> 1 math.sqrt(s)

/usr/local/lib/python3.6/dist-packages/sympy/core/expr.py in __float__(self)
    323         if result.is_number and result.as_real_imag()[1]:
    324             raise TypeError("can't convert complex to float")
--> 325         raise TypeError("can't convert expression to float")
    326 
    327     def __complex__(self):

TypeError: can't convert expression to float

您的错误的回溯(您应该已经显示!!)与此类似。

改用sympy.sqrt

In [29]: sqrt(s)                                                                         
Out[29]: √s

math.sqrt(和其他函数)是一个数字运算符。它需要一个数字,并返回一个。给它一个Symbol 会产生这个错误。

将数字函数与符号函数混合时要小心。这适用于 math 以及 numpyscipy(您导入但不使用)。

【讨论】:

    猜你喜欢
    • 2020-12-26
    • 1970-01-01
    • 2019-10-30
    • 1970-01-01
    • 1970-01-01
    • 2017-03-20
    • 2014-12-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多