def sawtooth ( nf ): #*****************************************************************************80 # ## sawtooth() plots a sawtooth function and a Fourier approximation to it. # # Licensing: # # This code is distributed under the MIT license. # # Modified: # # 31 January 2025 # # Author: # # John Burkardt # # Input: # # integer nf: the number of Fourier functions to use in approximating. # import matplotlib.pyplot as plt import numpy as np # # The sawtooth function has a period of 2 pi. # We sample the function over two periods. # nx = 51 x = np.linspace ( - np.pi, 3.0 * np.pi, nx ) s = 1.5 + ( ( x + np.pi ) % ( 2.0 * np.pi ) ) / np.pi sn = 2.5 for n in range ( 1, nf + 1 ): sn = sn + 2.0 / np.pi * ( -1.0 ) ** ( n + 1 ) * np.sin ( n * x ) / n print ( '' ) print ( ' Fourier approximation error for order n = ', nf ) print ( ' Max norm = ', np.linalg.norm ( s - sn, np.inf ) ) print ( ' L2 norm = ', np.linalg.norm ( s - sn, 2 ) ) # # Display plot of S, SN, S-SN # plt.clf ( ) plt.plot ( x, s, 'b' ) plt.plot ( x, sn, 'g' ) plt.plot ( x, s - sn, 'r' ) plt.grid ( True ) plt.title ( str ( nf ) + ' term Fourier approximation to sawtooth' ) plt.legend ( [ 'Sawtooth', 'Approx', 'Error' ] ) filename = 'sawtooth.png' plt.savefig ( filename ) print ( ' Graphics saved as "' + filename + '"' ) plt.show ( ) plt.close ( ) return if ( __name__ == "__main__" ): nf = 4 sawtooth ( nf )