Skip to content

Instantly share code, notes, and snippets.

@komasaru
Last active March 28, 2018 04:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save komasaru/13764b6ca3d455ed6e527db34505ede5 to your computer and use it in GitHub Desktop.
Save komasaru/13764b6ca3d455ed6e527db34505ede5 to your computer and use it in GitHub Desktop.
Python script to expand Fourier's series.
#! /usr/local/bin/python3.6
"""
Fourier's series expansion
f(t) = -1 (-pi < t <= 0 )
1 ( 0 < t <= pi)
"""
import math
import sys
import traceback
class FourierSeriesExpansion:
N = 3 # Number of items
CSV_FILE = "FourierSeriesExpansion.csv"
def expand_fourier_series(self):
""" Fourier's series expansion """
try:
with open(self.CSV_FILE, "w") as f:
f.write("t,f(t)\n")
y = 0
for t in range(int(math.pi * -1000), int(math.pi * 1000) + 1):
for i in range(1, self.N + 1):
y += self.__calc_term(i, t / 1000.0)
ft = 4 / math.pi * y
f.write("{:.3f},{:.6f}\n".format(t / 1000.0, ft))
y = 0
except Exception as e:
raise
def __calc_term(self, n, t):
""" Computation for each item
:param int n
:param int t
:return float
"""
try:
return math.sin((2 * n - 1) * t) / (2 * n - 1)
except Exception as e:
raise
if __name__ == '__main__':
try:
obj = FourierSeriesExpansion()
obj.expand_fourier_series()
except Exception as e:
traceback.print_exc()
sys.exit(1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment