Skip to content

Instantly share code, notes, and snippets.

@TestSubjector
Created September 2, 2018 06:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save TestSubjector/59ab7835320296269eccc6a6f6c2d2a1 to your computer and use it in GitHub Desktop.
Save TestSubjector/59ab7835320296269eccc6a6f6c2d2a1 to your computer and use it in GitHub Desktop.
Quick gist for two numerical methods to compute derivatives, mainly to show the error they generate (vs step size) as a plot
import numpy as np
import cmath
import matplotlib.pyplot as plt
def input_function(x):
return cmath.log(x)
def input_deravative_function(x):
return 1/x
def ctse(standard_input, delta_x):
return (input_function(complex(standard_input, delta_x)).imag)/delta_x
def main():
standard_input = 5
print("Start")
standard_output = input_deravative_function(standard_input)
print(standard_output)
x_range = np.logspace(-0.02, -14.4, num=500)
y_range = []
for index in range(len(x_range)):
y_range.append(abs(input_deravative_function(standard_input) - ctse(standard_input, x_range[index])))
# print(y_range)
plt.plot(x_range, y_range)
plt.xscale('log')
plt.xlabel('Img Step Size')
plt.ylabel('Error')
plt.show()
if __name__ == '__main__':
main()
import numpy as np
import math
import matplotlib.pyplot as plt
def input_function(x):
return math.log(x)
def input_deravative_function(x):
return 1/x
def forward_difference(standard_input, delta_x):
return (input_function(standard_input + delta_x) - input_function(standard_input))/ delta_x
def main():
standard_input = 5
print("Start")
standard_output = input_deravative_function(standard_input)
print(standard_output)
x_range = np.logspace(-0.02, -14.4, num=500)
y_range = []
for index in range(len(x_range)):
y_range.append(abs(input_deravative_function(standard_input) - forward_difference(standard_input, x_range[index])))
# print(y_range)
plt.plot(x_range, y_range)
plt.xscale('log')
plt.xlabel('Step Size')
plt.ylabel('Error')
plt.show()
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment