Fourier Expansion

63 views
Skip to first unread message

Davide Sandona'

unread,
Aug 25, 2020, 8:56:28 AM8/25/20
to sympy
Hello everyone,

Today I decided to refresh my knowledge of Fourier Expansion. I tried to use Sympy but I'm not sure if the result is correct or if I did something wrong, so I need a fresh pair of eyes on this :)
I was following the "Fourier Series of a Square Wave" in the Wolfram documentation [1], and I compare the result with Sympy. Here is the code and the picture.

x, n = symbols("x, n")
N
= 10
expr
= 2 * (Heaviside(x / 2) - Heaviside(x / 2 - 1)) - 1
fs
= expr.fourier_series()
wolfram
= 4 / pi * sin(n * pi * x / 2) / n
wolfram_expr
= 0
for i in range(1, N + 1):
   
if i % 2 != 0:
        wolfram_expr
+= (4 / pi * sin(n * pi * x / 2) / n).subs(n, i)
plot
(expr, fs.truncate(N), wolfram_expr, (x, -5, 5))

Figure 70.png




Did I do something wrong?
Thanks for you time! :)

mikhae...@umontpellier.fr

unread,
Aug 25, 2020, 12:48:20 PM8/25/20
to sympy
Dear Sandona,

  I am not a skilled Sympy user. However, I guess the fact that you do not give the periodicity does not allow sympy to compute the Fourier Series. I did this that seems satisfactory :

from sympy import *
x, n = symbols("x, n")
N = 10
expr = 2 * (Heaviside(x / 2) - Heaviside(x / 2 -1)) - 1
fs = fourier_series(expr,(x,-2,2))
wolfram = 4 / pi * sin(n * pi * x / 2) / n
wolfram_expr = 0
for i in range(1, N + 1):
    if i % 2 != 0:
        wolfram_expr += (4 / pi * sin(n * pi * x / 2) / n).subs(n, i)
plot(expr, fs.truncate(N/2), wolfram_expr, (x, -5, 5))

Moreover, I guess (I did not check in Sympy documentation) that Sympy only displays non-zero harmonics on "truncate" ?

Hope this helps,
   Mike


Davide Sandona'

unread,
Aug 25, 2020, 3:42:17 PM8/25/20
to sy...@googlegroups.com
Hello Mike,

thank you very much, you really helped me! I was too focused exploring the different methods, and the solution was just under my nose. Thank you! :)

Of course, the example I've chosen (the square wave) takes a tremendous amount of time to be solved by Sympy. Anyway, I tried a sawtooth wave and it works great! Thank you again!

Davide.


--
You received this message because you are subscribed to the Google Groups "sympy" group.
To unsubscribe from this group and stop receiving emails from it, send an email to sympy+un...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/sympy/44d21160-2242-4b1c-9d45-7436e0935181n%40googlegroups.com.

mikhae...@umontpellier.fr

unread,
Aug 25, 2020, 4:30:29 PM8/25/20
to sympy
Happy it helped ;-)
Reply all
Reply to author
Forward
0 new messages