medajibka

method_Gaussian

May 11th, 2022 (edited)
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.28 KB | None | 0 0
  1. import matplotlib.pyplot as plt
  2. import numpy as np
  3. from sympy import Symbol, Integral, exp, log
  4. from scipy.special import roots_legendre
  5.  
  6. def function(x):
  7.     f = 4 * np.sin(x * x) - np.log(x + 4)
  8.     return f
  9.  
  10.  
  11. def foo():
  12.     _x = Symbol('x')
  13.     return Integral(exp(_x) * log(_x), (_x, 1, 2))
  14.  
  15. def method_Gaussian(a, b, n):
  16.     b_a_half_size = (b - a) / 2
  17.     a_b_half_sum = (a + b) / 2
  18.  
  19.     roots, weights = roots_legendre(n)
  20.  
  21.     _sum = 0
  22.     for i in range(n):
  23.         _sum += weights[i] * function(a_b_half_sum + b_a_half_size * roots[i])
  24.     _sum *= b_a_half_size
  25.  
  26.     print(str('Gaussian quadrature: ') + str(_sum))
  27.  
  28.  
  29. def draw_function():
  30.     x = np.arange(0.1, 2.5, 0.07)
  31.     f = function(x)
  32.  
  33.     line = plt.plot(x, f, color='limegreen')
  34.  
  35.     plt.fill_between(x, f, color='palegreen', where=(x < 2) & (f > 0))
  36.     plt.grid()
  37.  
  38.     plt.setp(line, color="limegreen", linewidth=1.5)
  39.     plt.gca().spines["left"].set_position("zero")
  40.     plt.gca().spines["bottom"].set_position("zero")
  41.     plt.gca().spines["top"].set_visible(False)
  42.     plt.gca().spines["right"].set_visible(False)
  43.  
  44.     plt.show()
  45.    
  46.    
  47. def main():
  48.     _a = 1
  49.     _b = 2
  50.     _n = 6
  51.    
  52.     method_Gaussian(_a, _b, _n)
  53.     draw_function()
  54.    
  55. if __name__ == '__main__':
  56.     main()
Add Comment
Please, Sign In to add comment