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
|
# More integral
### Newton-Cotes Algorithms for Equations
### Adaptive Quadrature
## Problems
## Numerical Integration to Compute Work
In physics we've learned that work is computed
$$
Work = force * distance
$$
This can be written in int's integral form:
$$
W = \int{F(x)dx}
$$
If F(x) is easy to integrate, we could solve this problem analytically. However, a realistic problem the force may not be available to you as a function, but rather, tabulated data. Suppose some measurements were take of when a weighted box was pulled with a wire. If we data of the force on the wire and the angle of the wire from the horizontal plane.
| x (ft) | F(x) (lb) | θ (rad) | F(x) cos θ |
| ------ | --------- | ------- | ---------- |
| 0 | 0.0 | 0.50 | 0.0000 |
| 5 | 9.0 | 1.40 | 1.5297 |
| 10 | 13.0 | 0.75 | 9.5120 |
| 15 | 14.0 | 0.90 | 8.7025 |
| 20 | 10.5 | 1.30 | 2.8087 |
| 25 | 12.0 | 1.48 | 1.0881 |
| 30 | 5.0 | 1.50 | 0.3537 |
| | | | |
Use the trapezoidal rule to compute the work done on the box.
## Implementing the Composite Trapezoidal Rule
Implement a Python function to approximate integrals using the trapezoidal rule.
```python
import numpy as np
def trapz(f, a, b, n):
x = np.linspace(a, b, n+1)
y = f(x)
h = (b - a) / n
return h * (0.5*y[0] + y[1:-1].sum() + 0.5*y[-1])
# Example tests
f1 = np.sin
I_true1 = 2.0 # ∫_0^π sin(x) dx
for n in [4, 8, 16, 32]:
print(n, trapz(f1, 0, np.pi, n))
```
Compare the results for increasing $n$ and observe how the error decreases with $O(h^2$).
|