MCPcopy Index your code
hub / github.com/cfgnunes/numerical-methods-python / backward_difference

Function backward_difference

differentiation.py:6–37  ·  view source on GitHub ↗

Calculate the first derivative. All values in 'x' must be equally spaced. Args: x (numpy.ndarray): x values. y (numpy.ndarray): y values. Returns: dy (numpy.ndarray): the first derivative values.

(x, y)

Source from the content-addressed store, hash-verified

4
5
6def backward_difference(x, y):
7 """Calculate the first derivative.
8
9 All values in 'x' must be equally spaced.
10
11 Args:
12 x (numpy.ndarray): x values.
13 y (numpy.ndarray): y values.
14
15 Returns:
16 dy (numpy.ndarray): the first derivative values.
17 """
18 if x.size < 2 or y.size < 2:
19 raise ValueError("'x' and 'y' arrays must have 2 values or more.")
20
21 if x.size != y.size:
22 raise ValueError("'x' and 'y' must have same size.")
23
24 def dy_difference(h, y0, y1):
25 return (y1 - y0) / h
26
27 n = x.size
28 dy = np.zeros(n)
29 for i in range(0, n):
30 if i == n - 1:
31 hx = x[i] - x[i - 1]
32 dy[i] = dy_difference(-hx, y[i], y[i - 1])
33 else:
34 hx = x[i + 1] - x[i]
35 dy[i] = dy_difference(hx, y[i], y[i + 1])
36
37 return dy
38
39
40def three_point(x, y):

Callers

nothing calls this directly

Calls 1

dy_differenceFunction · 0.85

Tested by

no test coverage detected