Maifee Ul Asad
Maifee Ul Asad

Reputation: 4579

sympy TypeError: can't convert expression to float

I'm trying to calculate integration using sympy, here is my code:

import sympy as sp
from scipy.integrate import quad
import math
def f(x):
    return math.exp(-2.0*math.pi*sp.I*x*n)
x = sp.Symbol('x')
n = sp.Symbol('n')
res,err = quad(f,0,1)
print(res)

It gives me TypeError: can't convert expression to float inside f(x), how can I solve this ?

Trying to solve this : Integration of e^(-2*pi*n*I*x) in range of 0 to 1 with respect to x

Doesn't support math ajax : $$\int_0^1 e^{-2\pi inx} dx$$

if I just write math.exp(-2.0*math.pi*x) it works, but if I write math.exp(-2.0*math.pi*sp.I) or math.exp(-2.0*math.pi*n) it doesn't or for other combinations.

Upvotes: 2

Views: 2377

Answers (1)

JohanC
JohanC

Reputation: 80509

Sympy can not work with math imports, you need specific sympy functions. Neither do sympy and scipy play together well.

A pure sympy solution:

import sympy as sp

def f(x):
    return sp.exp(-2.0*sp.pi*sp.I*x*n)

x = sp.Symbol('x')
n = sp.Symbol('n')

res = sp.integrate(f(x), (x, 0, 1))

Output:

Piecewise((-0.5*I/(pi*n) + 0.5*I*exp(-2.0*I*pi*n)/(pi*n), (n > -oo) & (n < oo) & Ne(n, 0)), (1, True))

Use n = sp.Symbol('n', nonzero=True) if you know n will never be zero, which simplifies the output to just -0.5*I/(pi*n) + 0.5*I*exp(-2.0*I*pi*n)/(pi*n)

Afterwards, you can use sympy's lambdify to convert the result to a normal python function of n.

Upvotes: 3

Related Questions