#!/usr/bin/env python # coding: utf-8 # # Trapezoid vs Gauss quadrature for periodic function # Let us compute # $$ # \int_0^{2\pi} \exp(\sin x) dx # $$ # In[5]: get_ipython().run_line_magic('matplotlib', 'inline') get_ipython().run_line_magic('config', "InlineBackend.figure_format = 'svg'") from scipy.integrate import fixed_quad,trapz import numpy as np import matplotlib.pyplot as plt f = lambda x: np.exp(np.sin(x)) a,b = 0.0,2*np.pi qe = 7.954926521012844 # Exact integral n,N = 2,10 e1,e2,nodes = np.zeros(N),np.zeros(N),np.zeros(N) for i in range(N): x = np.linspace(a,b,n) val = trapz(f(x),dx=(b-a)/(n-1)) e1[i] = np.abs(val - qe) val = fixed_quad(f,a,b,n=n) nodes[i] = n e2[i] = np.abs(val[0]-qe) print('%5d %20.10e %20.10e' % (n,e1[i],e2[i])) n = n+2 plt.figure() plt.semilogy(nodes,e1,'o-') plt.semilogy(nodes,e2,'*-') plt.legend(('Trapezoid','Gauss')) plt.xlabel('n') plt.ylabel('Error'); # Trapezoid error converges at exponential rate !!!