1
$\begingroup$

how to find slope at certain points circled in blue in below curve ? Are these below 2 approaches valid ? though they give different results . How to automatically find the points where the slope changes drastically in curve like around at point 5,6 in below graph

x=[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, ]

y=[512, 256, 128, 64 , 32 , 16 , 8  , 7  , 6  , 5  , 4  , 3  , 2  , 1  ]
  1. Numpy gradient give below result

np.gradient(y)

[-256. , -192. ,  -96. ,  -48. ,  -24. ,  -12. ,   -4.5,   -1. ,-1. ,   -1. ,   -1. ,   -1. ,   -1. ,   -1. ]

can we use numpy.gradient to find the slope of curve ? since finding slope of line and curve is bit different Shown in this link

2.Using custom slope function

def slope(x1, y1, x2, y2):
    m = (y2-y1)/(x2-x1)
    return m


slope_value=[]
for i in range(len(y)):
    i += 1
    v=slope(y[i], x[i], y[i-1], x[i-1])
    print(i,v)
    slope_value.append(v)



result: [-0.00390625,  -0.0078125,  -0.015625,  -0.03125,  -0.0625,  -0.125,  -1.0,  -1.0,  -1.0,  -1.0,  -1.0,  -1.0,  -1.0]

enter image description here

$\endgroup$
0
0
$\begingroup$

The numpy calculation is the correct one to use, but may be a bit tricky to understand how it is calculated

Your custom calculation is accidentally returning the inverse slope, the x and y values are reversed in the slope function (x1 -> y[i], etc). The slope should be delta_y/delta_x

def slope(x1, y1, x2, y2):
v=slope(y[i], x[i], y[i-1], x[i-1])

Also, you are calculating the slope at x = 1.5, 2.5, etc but numpy is calculating the slope at x = 1, 2, 3

In the gradient calculation, numpy is calculating the gradient at each x value, by using the x-1 and x+1 values and dividing by the difference in x which is 2. You are calculating the inverse of the x + .5 values.

x=[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, ]

y=[512, 256, 128, 64 , 32 , 16 , 8  , 7  , 6  , 5  , 4  , 3  , 2  , 1  ]

numpy answer:

[-256. , -192. ,  -96. ,  -48. ,  -24. ,  -12. ,   -4.5,   -1. ,-1. ,   -1. ,   -1. ,   -1. ,   -1. ,   -1. ]

each calculation in numpy function:

-256 = (-256)/1 there is no x-1 value so the default is to use x
-192 = (128-512)/2
-96 = (64-256)/2
...

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.