'Calculate average slope over a period of time with python
I would like to calculate the average slope of multiple numbers. For example: I've been given 5 numbers (eg. 1.1523, 1.4626, 1.5734, 1.8583, 1.6899). I get a new number every 15 minutes and delete the oldest and want to calculate again the average slope.
I've already seen formulas but I don't really get how to calculate it when like the imaginary x-axis is the time. Like I have: X: 14:00, 14:15, 14:30, 14:45, 15:00 Y: 1.1523, 1.4626, 1.5734, 1.8583, 1.6899
Solution 1:[1]
Assuming all times are in HH:MM format and we don't need to worry about passing midnight, this should work:
X = ['14:00', '14:15', '14:30', '14:45', '15:00']
Y = [1.1523, 1.4626, 1.5734, 1.8583, 1.6899]
minutes = [int(s[:2]) * 60 + int(s[3:]) for s in X]
slope = (Y[-1] - Y[0]) / ((minutes[-1] - minutes[0]) / 60)
print(slope)
slopes = [(Y[i] - Y[i - 1]) / ((minutes[i] - minutes[i - 1]) / 60) for i in range(1, len(X))]
print(slopes)
averageSlope = sum(slopes) / (len(X) - 1)
print(averageSlope)
Results:
0.5375999999999999
[1.2411999999999992, 0.44320000000000004, 1.1396000000000006, -0.6736000000000004]
0.5375999999999999
Solution 2:[2]
I could be wrong, but isn't average slope determined the same way as average velocity - which is Delta d / Delta t? If that is the case, shouldn't it be Delta Y / Delta X?
from datetime import datetime
X = ['14:00', '14:15', '14:30', '14:45', '15:00']
Y = [1.1523, 1.4626, 1.5734, 1.8583, 1.6899]
today = datetime.now()
avg = []
for i in range(len(X) - 1):
e = X[i + 1].split(":")
e = datetime(today.year, today.month, today.day, int(e[0]), int(e[1]))
s = X[i].split(":")
s = datetime(today.year, today.month, today.day, int(s[0]), int(s[1]))
deltaX = e - s
deltaY = Y[i + 1] - Y[i]
ans = (deltaY / deltaX.seconds) / 60
avg.append(f'{ans:.9f}')
print(avg)
['0.000005746', '0.000002052', '0.000005276', '-0.000003119']
Consider this data:
1 minute(s) 1 meter(s)
2 minute(s) 2 meter(s)
3 minute(s) 3 meter(s)
You should have a slope of 1 meter/minute, no matter how you cut the cake.
Likewise for this:
1 minute(s) 2 meter(s)
2 minute(s) 3 meter(s)
3 minute(s) 5 meter(s)
From 2 to 1 minutes, the average is 1 meters/minute, from 3 to 2 minutes its 2 meters/minute, and from 3 to 1 minutes its 1.5 meters/minute.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | constantstranger |
| Solution 2 |
