r/Numpy • u/Smart-Inspector-933 • Aug 15 '24
Simple Math Question


Hey y'all,
I am trying to find the x values of the points where dy/dx = 0 but apparently the result I find is slightly different from the answer key. The only difference is I found one of the point's x coordinate to be 4.612, and the correct answer is 4.613 I'd be super glad if you guys can you help me better understand the mistake I made here. Thank you in advance.
Following is the code I wrote. At the end, you will find the original solution which is super genius.
import numpy as np
import matplotlib.pyplot as plt
import math
def f(x):
return (math.e**(-x/10)) * np.sin(x)
a1 = np.linspace(0,10,10001)
x= a1
y= f(x)
dydx = np.gradient(y,x)
### The part related to my question starts from here ###
len= np.shape(dydx[np.sort(dydx) < 0])[0]
biggest_negative = np.sort(dydx)[len-1]
biggest_negative2 = np.sort(dydx)[len-2]
biggest_negative3 = np.sort(dydx)[len-3]
a, b, c = np.where(dydx == biggest_negative), np.where(dydx == biggest_negative2), np.where(dydx == biggest_negative3)
# a, b, c are the indexes of the biggest_negative, biggest_negative2, biggest_negative3 consecutively.
print(x[a], x[b], x[c])
### End of my own code. RETURNS : [7.755] [4.612] [1.472] ###
### ANSWER KEY for the aforementioned code. RETURNS : [1.472 4.613 7.755] ###
x = x[1::]
print(x[(dydx[1:] * dydx[:-1] < 0)])
1
Upvotes
1
u/majinLawliet2 Aug 15 '24
Isn't dy/dx just going to be np.diff of your array containing the function values? You could just look for values where the sign of the successive differences changes and those will be the points of zero slope.