Reputation: 175
I got data and showed it as a graph with matplotlib. and I reduced noise and under is the pictures of them.
and now I want to know the gradient of each points, so I tried to do differential in my graph.
but when I found about that, I just got information of how to do that when you have the equation of the graph.
maybe this one can be work(code under), but how can I got the value of f(x+h) and f(x-h)?
def numerical_diff(f, x):
h = 1e-4
return (f(x+h) - f(x-h)) / (2*h)
sorry for poor English and thank you for reading. I'll wait for your answer. help me pls 😢
Upvotes: 1
Views: 393
Reputation: 323
I understand that you are attempting to do numeric differential, this can be accomplished in many ways, but the most simple is to use the equation that you have written.
def numerical_dif(y_data: list) -> list:
differential = []
for i in range(len(y_data) - 1):
differential.append(y_data[i+1]-y_data[i])
return differential
This assumes equidistant data points but could be easily modified to take x-axis position as well. If you are using NumPy, then the simplest differential is numpy.diff()
If you are looking for more complex solution look here Univariate spline
Upvotes: 1
Reputation: 13206
numpy np.gradient
would work on the data array you use to plot the data. You also need to supply dx which is the change between your variables,
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0, 4*np.pi, 100)
dx = x[1] - x[0]
y = np.sin(x)
plt.plot(x, y)
plt.plot(x, np.gradient(y, dx))
plt.show()
Numerical derivatives are noisy You could also consider spline fitting and taking derivatives of these for smoother plots,
from scipy.interpolate import UnivariateSpline
spl = UnivariateSpline(x, y, k=4, s=0)
diffspl = spl.derivative()
plt.plot(x, spl(x), '--')
plt.plot(x, diffspl(x), '--')
plt.show()
Upvotes: 3