Python script to expand Fourier's series.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#! /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