#!/usr/bin/env python # coding: utf-8 # # # # # Creating the Finite-Difference Table for Centered First and Second Derivatives, from 2nd through 10th-Order Accuracy # # # # ## *Courtesy Brandon Clark* # In[1]: print("Installing astropy, needed for creating the output table. Please wait a few seconds...") get_ipython().system('pip install -U pip astropy > /dev/null') print("astropy installed.") # Step 0: Import needed modules import numpy as np import finite_difference as fin from astropy.table import Table # Step 1: Set the maximum finite-difference accuracy order computed in the table max_fdorder = 10 # Step 2: Set up table parameters # One column for deriv order, one for deriv accuracy, and max_fdorder+1 numcols = 2 + max_fdorder + 1 # 8 rows: max_fdorder accuracy orders per derivative order, times 2 derivative orders (first & second derivative) numrows = int(max_fdorder/2 * 2) # Center column index of table will be at 2 + max_fdorder/2 (zero-offset indexing) column_corresponding_to_zero_fd_point = 2 + int(max_fdorder/2) # The table is initialized as a matrix of zeroes in numpy... numpy_matrix = np.zeros((numrows, numcols), dtype=object) # Then we replace all elements with the empty string to match the Wikipedia article. for row in range(numrows): for col in range(numcols): numpy_matrix[row,col] = "" # Step 3: Construct the first-order derivative finite difference coefficients rowcount = 0 for fdorder in range(2, max_fdorder+1, 2): # loop runs from 2 to max_fdorder inclusive, skipping odd orders. numpy_matrix[rowcount, 0] = "1st" numpy_matrix[rowcount, 1] = fdorder fdcoeffs, fdstencl = fin.compute_fdcoeffs_fdstencl("D0", fdorder) for i in range(fdorder): numpy_matrix[rowcount, column_corresponding_to_zero_fd_point + fdstencl[i][0]] = fdcoeffs[i] rowcount += 1 # Step 4: Construct the second-order derivative finite difference coefficients for fdorder in range(2, max_fdorder+1, 2): # loop runs from 2 to max_fdorder inclusive, skipping odd orders. numpy_matrix[rowcount, 0] = "2nd" numpy_matrix[rowcount, 1] = fdorder fdcoeffs, fdstencl = fin.compute_fdcoeffs_fdstencl("DD00", fdorder) for i in range(fdorder+1): numpy_matrix[rowcount, column_corresponding_to_zero_fd_point + fdstencl[i][0]] = fdcoeffs[i] rowcount += 1 # Step 5: Construct an astropy table from the numpy matrix with the following header info, and then print it: colnames = ['Derivative','Accuracy'] for i in range(-int(max_fdorder/2),int(max_fdorder/2)+1): colnames.append(str(i)) table = Table(numpy_matrix, names=colnames) table.pprint(max_width=-1)