Created
December 29, 2019 16:13
-
-
Save accessnash/87f95b6d5d3f279c062d4d0bac0fb815 to your computer and use it in GitHub Desktop.
Solving for the 1st & 2nd derivatives of a given polynomial using Finite differences methods
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # -*- coding: utf-8 -*- | |
| """ | |
| Created on Sun Dec 29 16:51:25 2019 | |
| @author: DASA0 | |
| """ | |
| """ find the 1st & 2nd derivatives of the polynomial at x = 0.1: | |
| f(x) = 0.1x^5 -0.2x^3 + 0.1x - 0.2 """ | |
| f = lambda x: 0.1*x**5 - 0.2*x**3 + 0.1*x - 0.2 | |
| h = 0.05 | |
| x = 0.1 | |
| # Forward differences approximation | |
| dff1 = (f(x+h) - f(x))/h | |
| dff2 = (f(x+2*h) - 2*f(x+h) + f(x))/h**2 | |
| print('Solution by forward differences:') | |
| print('f\'(%f) = %f'%(x,dff1)) | |
| print('f\'\'(%f) = %f'%(x,dff2)) | |
| # Central differences approximation | |
| dfc1 = (f(x+h)-f(x-h))/(2*h) | |
| dfc2 = (f(x+h)-2*f(x)+f(x-h))/h**2 | |
| print('\nSolution by central differences:') | |
| print('f\'(%f) = %f'%(x,dfc1)) | |
| print('f\'\'(%f) = %f'%(x,dfc2)) | |
| # Backward differences approximation | |
| dfb1 = (f(x)-f(x-h))/h | |
| dfb2 = (f(x)-2*f(x-h)+f(x-2*h))/h**2 | |
| print('\nSolution by backward differences:') | |
| print('f\'(%f) = %f'%(x,dfb1)) | |
| print('f\'\'(%f) = %f'%(x,dfb2)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment