Search code examples
pythontypeerrorsympysymbolic-integration

TypeError: can't convert expression to float - definite integral sympy


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)

Solution

  • To illustrate `@Oscar's comment

    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
    

    The traceback for your error (which you should have shown!!) is similar to this.

    Using the sympy.sqrt instead:

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

    math.sqrt (and other functions) is a numeric operator. It expects a number, and returns one as well. Giving it a Symbol produces this error.

    Be careful when mixing numeric functions with symbolic ones. That applies to math and also numpy and scipy (which you import but don't use).