Skip to content

Instantly share code, notes, and snippets.

@assyrianic
Created July 6, 2024 02:15
Show Gist options
  • Save assyrianic/274af82debc4d3eb7daae2c880057f39 to your computer and use it in GitHub Desktop.
Save assyrianic/274af82debc4d3eb7daae2c880057f39 to your computer and use it in GitHub Desktop.
a python script for estimating derivatives from a table of inputs and outputs.
# derivative estimator.
cont = True
while cont:
xs, ys = [], []
while True:
a = input('enter X: ')
if len(a) < 1:
break
xs.append(float(a))
xlen = len(xs)
if xlen <= 1:
print('too little Xs. Try again.')
continue
while True:
a = input('enter Y(X): ')
if len(a) < 1:
break
ys.append(float(a))
ylen = len(ys)
if ylen != xlen:
print('ylen =/= xlen.')
else:
slopes = []
for idx in range(1, xlen):
slopes.append((ys[idx] - ys[idx-1]) / (xs[idx] - xs[idx-1]))
avg_slopes = []
for x in range(1, len(slopes)):
avg_slopes.append((slopes[x] + slopes[x-1]) / 2)
idx = 0
for x in range(1, xlen):
print(f'({ys[x]} - {ys[x-1]} = {ys[x] - ys[x-1]}) / ({xs[x]} - {xs[x-1]} = {xs[x] - xs[x-1]})) = {slopes[idx]}')
idx += 1
idx = 1
for x in range(1, xlen-1):
print(f'derivative for {xs[x]}: ({slopes[idx]} + {slopes[idx-1]}) / 2 = {(slopes[idx] + slopes[idx-1]) / 2}')
idx += 1
cont = len(input('continue? ')) > 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment