# 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$).