Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # -*- coding: utf-8 -*-
- from math import *
- from numpy import *
- import matplotlib.pyplot as plt
- def trapezoidal(f, a, b, n):
- h = float(b - a)/n
- result = 0.5*(f(a) + f(b))
- for i in range(1, n):
- result += f(a + i*h)
- result *= h
- return result
- def integrate_coeffs(f, N, M):
- result = zeros(N)
- for n in range(1, N+1):
- result[n-1] = trapezoidal(lambda x: 1.0/pi*f(x)*sin(n*x), -pi, pi, M)
- return result
- def plot_approx(f, N, M):
- x = linspace(-pi, pi, num=1000)
- y = array([f(i) for i in x])
- bn = integrate_coeffs(f, N, M)
- y_approx = array([sum(array([bn[j-1]*sin(j*i) for j in range(1, N+1)])) for i in x])
- plt.plot(x, y, color='r', label="initial function")
- plt.plot(x, y_approx, color='g', label="approximation")
- plt.legend(loc="best")
- plt.show()
- f1 = lambda x: 1/pi*x
- integrate_coeffs(f, 3, 100)
- plot_approx(f, 24, 1000)
- f2 = lambda x: exp(-(x-pi))
- plot_approx(f2, 100, 1000)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement