typst-itmo/chastotnie-methods/lab1/fourier.py

63 lines
2.2 KiB
Python
Raw Permalink Normal View History

2024-09-11 02:42:57 +00:00
from sys import argv
from math import pi
2024-09-16 21:28:11 +00:00
from math import e
function_formulas = [
# 1. Square wave
{
'an': lambda n: 3 if n == 0 else 0,
2024-09-11 02:42:57 +00:00
'bn': lambda n: 0 if n % 2 == 0 else 2 / (pi * n),
'cn': lambda n: 3 if n == 0 else (0 if n % 2 == 0 else 1j / (pi * n))
},
# 2. Even func
{
'an': lambda n: 0 if n == 0 else (0 if n % 2 == 0 else 8 / (pi ** 2 * n ** 2)),
'bn': lambda n: 0,
'cn': lambda n: 0 if n == 0 else (0 if n % 2 == 0 else 4 / (pi ** 2 * n ** 2))
},
# 3. Odd func
{
'an': lambda n: 0,
'bn': lambda n: 0 if n == 0 else 2 * (-1) ** (n + 1) / (pi * n),
'cn': lambda n: 0 if n == 0 else (-1) ** n / (pi * n) if n > 0 else (-1) ** (n + 1) / (pi * n)
},
# 4. Not odd and not even func
{
'an': lambda n: -2/3 if n == 0 else (8 / (pi ** 2 * n ** 2) if n % 2 == 0 else 0),
'bn': lambda n: 0 if n % 2 == 0 else -48 / (pi ** 3 * n ** 3),
'cn': lambda n: -1/3 if n == 0 else (
(4 / (pi ** 2 * n ** 2) if n % 2 == 0 else 24j / (pi ** 3 * n ** 3))
if n > 0 else
(4 / (pi ** 2 * n ** 2) if n % 2 == 0 else -24j / (pi ** 3 * n ** 3))
)
2024-09-16 21:28:11 +00:00
},
# 5. Complex func
{
'an': lambda n: 0,
'bn': lambda n: 0,
'cn': lambda n: 0 if n == 0 else (
complex(-pi * n / 4, -1 - pi * n / 4) * e ** (1j * pi * n / 4)
+ (1j + 1) * e ** (-1j * pi * n / 4)
+ (1j - 1) * e ** (-3j * pi * n / 4)
+ (-1j - 1) * e ** (-5j * pi * n / 4)
+ complex(1 + pi * n / 4, pi * n / 4) * e ** (-7j * pi * n / 4)
) / (pi ** 2 * n ** 2 / 2)
}
]
2024-09-11 02:42:57 +00:00
index, nn = int(argv[1]), int(argv[2])
formulas = function_formulas[index - 1]
coefficients = {'an': [], 'bn': [], 'cn': []}
for coefficient in coefficients:
for n in range(0, nn + 1):
calc = formulas[coefficient](n)
coefficients[coefficient].append(f'{n}: {calc:.5g}')
if coefficient == 'cn' and n != 0:
calc = formulas[coefficient](-n)
coefficients[coefficient].insert(0, f'{-n}: {calc:.5g}')
for coefficient in coefficients:
print(f'{coefficient} values: ', coefficients[coefficient])