Athul Dev
Athul Dev

Reputation: 61

Fourier series of a box function using sympy

I tried this code but i m getting an error. And If possible pls tell me how to lambdify the defined funct CODE

from sympy.abc import x
from sympy import *

init_printing()
def func(y):
    if y>0:
        return 1
    elif y<0:
        return -1
    else:
        return 0
s = fourier_series(func(x), (x, -1, 1))
s = s.truncate(n=4)
s

"TypeError: cannot determine truth value of Relational" this is the error im getting Please help, Thank you.

Upvotes: 2

Views: 792

Answers (1)

JohanC
JohanC

Reputation: 80409

Note that sympy can only work with functions that are fully defined as a sympy expression. To emulate if - elif - else, Piecewise can be used. There is also a special function, Heaviside, that directly corresponds to your given function. Default, Heaviside(0) is undefined. However, the value for 0 can be provided as a second argument.

Using the Heaviside function doesn't seem to work in this case:

from sympy import Heaviside, fourier_series
from sympy.abc import x

s = fourier_series(Heaviside(x, 0), (x, -1, 1))
print(s)

This results in an unevaluated integral with which sympy can't do further operations:

FourierSeries(Heaviside(x, 0), (x, -1, 1), (Integral(Heaviside(x, 0), (x, -1, 1))/2, SeqFormula(cos(_n*pi*x)*Integral(cos(_n*pi*x)*Heaviside(x, 0), (x, -1, 1)), (_n, 1, oo)), SeqFormula(sin(_n*pi*x)*Integral(sin(_n*pi*x)*Heaviside(x, 0), (x, -1, 1)), (_n, 1, oo))))

Fortunately, with Piecewise, everything works as desired:

from sympy import lambdify, Piecewise, fourier_series
from sympy.abc import x

s = fourier_series(Piecewise((1, x > 0), (-1, x < 0), (0, True)), (x, -1, 1))

The function can be lambdified calling lambdify(x, s.truncate(n=4)), and then be used for example to draw curves via matplotlib:

import numpy as np
import matplotlib.pyplot as plt

for k in range(1, 7):
    s_np = lambdify(x, s.truncate(n=k))
    xs = np.linspace(-1, 1, 500)
    plt.plot(xs, s_np(xs), label=f'$n={k}$')
plt.autoscale(enable=True, axis='x', tight=True)
plt.legend()
plt.show()

resulting plot

Upvotes: 3

Related Questions