1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
|
# Numerical Differentiation
Finding a derivative of tabular data can be done using a finite difference. Here we essentially pick two points on a function or a set of data points and calculate the slope from there. You may have done this before in spreadsheets, we're going to do this using python. Let's imagine a time range $t$ as a vector such that $\vec{t}$ = $\pmatrix{t_0, t_1, t_2, ...}$ and a displacement domain as a function of time. We can represent the range and domain as two python arrays `t` and `s` respectively.
```python
import numpy as np
# Initiate time domain
t = np.linspace(0, 2, 100)
s = 34 * np.exp(3 * t)
```
Then we can use the following methods to approximate the definitive derivatives as follows.
## Forward Difference
Uses the point at which we want to find the derivative and a point forwards in the array.
$$
f'(x_i) = \frac{f(x_{i+1})-f(x_i)}{x_{i+1}-x_i}
$$
*Note: If we apply this to an array, consider what happens at the last point.*
```python
# Forward difference using python arrays
dsdt = (y[1:] - y[:-1]) / (x[1:] - x[:-1])
import matplotlib.pyplot as plt
# Plot the function
plt.plot(x, s, label=r'$y(x)$')
plt.plot(x, dsdt, label=b'$/frac{ds}{dt}$')
plt.xlabel('Time (t)')
plt.ylabel('Displacement (s)')
plt.title('Plot of $34e^{3t}$')
plt.grid(True)
plt.legend()
plt.show()
```
## Backwards Difference
Uses the point at which we want to find and the previous point in the array.
$$
f'(x_i) = \frac{f(x_{i})-f(x_{i-1})}{x_i - x_{i-1}}
$$
```python
dsdt = (y[1:] - y[:-1]) / (x[1:] - x[:-1])
# Plot the function
plt.plot(x, y, label=r'$y(x)$')
plt.plot(x, dydx, label=b'$/frac{ds}{dt}$')
plt.xlabel('x')
plt.ylabel('y')
plt.title('Plot of $34e^{3x}$')
plt.grid(True)
plt.legend()
plt.show()
```
## Central Difference
$$
f'(x_i) = \frac{f(x_{i+1})-f(x_{i-1})}{x_{i+1}-x_{i-1}}
$$
|