I have created a synthetic data using this code-
# x variable x_value = np.linspace(0,2*np.pi,1000) # y variable for i in x_value: y_value = np.sin(x_value) # create a dataframe with the x and y values data = pd.DataFrame({'x':x_value, 'y':y_value})
I would like to create a third column for derivative of x ( cos(x_value)) calculated manually using finite difference method- where for value of 1st row I have to use forward difference method, last row- backward difference and for the rest use central difference. My code is like this -
# differnce for xvalue, delta_x data['delta_x']= data['x'].diff(1) # resukts in 0.006289 # create an empty column data['deriv'] = '' # function for Central difference for row 2 to 2nd last row for i in range(1,len(data)-1): data['deriv'][i] = (data['y'][i+1]-data['y'][i-1])/(2*0.006289) # for the 1st row - forward difference data['deriv'][0] = (data['y'][1]-data['y'][0])/0.006289 # for the last row - backward difference data['deriv'].iloc[-1] = (data['y'].iloc[-1]-data['y'].iloc[-2])/0.006289
I am getting the desired output ( true derivate and calculated derivatives match) but I am getting this warning for the difference methods- SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame Also, I am looking for an efficient way to write this code. Thanks a lot in advance.
https://stackoverflow.com/questions/66753016/how-to-calculate-derivative-of-an-array-using-finite-difference-python March 23, 2021 at 03:55AM
没有评论:
发表评论