Advertisement
Guest User

Untitled

a guest
Jan 20th, 2017
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.98 KB | None | 0 0
  1. # -*- coding: utf-8 -*-
  2.  
  3. from math import *
  4. from numpy import *
  5. import matplotlib.pyplot as plt
  6.  
  7. def trapezoidal(f, a, b, n):
  8.     h = float(b - a)/n
  9.     result = 0.5*(f(a) + f(b))
  10.     for i in range(1, n):
  11.         result += f(a + i*h)
  12.     result *= h
  13.     return result
  14.  
  15. def integrate_coeffs(f, N, M):
  16.     result = zeros(N)
  17.     for n in range(1, N+1):
  18.         result[n-1] = trapezoidal(lambda x: 1.0/pi*f(x)*sin(n*x), -pi, pi, M)
  19.     return result
  20.  
  21. def plot_approx(f, N, M):
  22.     x = linspace(-pi, pi, num=1000)
  23.     y = array([f(i) for i in x])
  24.     bn = integrate_coeffs(f, N, M)
  25.     y_approx = array([sum(array([bn[j-1]*sin(j*i) for j in range(1, N+1)])) for i in x])
  26.     plt.plot(x, y, color='r', label="initial function")
  27.     plt.plot(x, y_approx, color='g', label="approximation")
  28.     plt.legend(loc="best")
  29.     plt.show()
  30.    
  31.    
  32.    
  33. f1 = lambda x: 1/pi*x
  34. integrate_coeffs(f, 3, 100)
  35. plot_approx(f, 24, 1000)
  36. f2 = lambda x: exp(-(x-pi))
  37. plot_approx(f2, 100, 1000)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement