# Tactiverge Academy — companion code for "Numerical integration and differentiation"
# Lesson: https://tactiverge.win/academy/computational-engineering/engineering-algorithms/numerical-integration-differentiation/
# Licence: MIT (see https://tactiverge.win/open-engineering/). Examples appear in lesson order.

# ── Example 1 ────────────────────────────────────────
times = [0.0, 0.5, 1.0, 1.5, 2.0, 2.5, 3.0]          # s
speeds = [0.0, 0.18, 0.31, 0.40, 0.42, 0.41, 0.40]   # m/s

distance = 0.0
for i in range(1, len(times)):
    dt = times[i] - times[i - 1]
    distance += 0.5 * (speeds[i] + speeds[i - 1]) * dt

print(f"Distance travelled: {distance:.3f} m")


# ── Example 2 ────────────────────────────────────────
import math

def trapezoid(f, a, b, n):
    """Integrate f from a to b using n equal trapezoids."""
    h = (b - a) / n
    total = 0.5 * (f(a) + f(b))
    for i in range(1, n):
        total += f(a + i * h)
    return total * h

for n in [4, 8, 16, 32]:
    estimate = trapezoid(math.sin, 0.0, math.pi, n)
    print(f"n = {n:2d}   estimate = {estimate:.6f}   error = {2 - estimate:.6f}")


# ── Example 3 ────────────────────────────────────────
import math

x = 1.0
exact = math.cos(x)

print(f"{'h':>8} {'forward error':>14} {'central error':>14}")
for h in [0.1, 0.01, 0.001]:
    forward = (math.sin(x + h) - math.sin(x)) / h
    central = (math.sin(x + h) - math.sin(x - h)) / (2 * h)
    print(f"{h:>8} {abs(forward - exact):>14.2e} {abs(central - exact):>14.2e}")


# ── Example 4 ────────────────────────────────────────
import math

x = 1.0
exact = math.cos(x)
for h in [1e-5, 1e-8, 1e-11, 1e-13]:
    central = (math.sin(x + h) - math.sin(x - h)) / (2 * h)
    print(f"h = {h:.0e}   central error = {abs(central - exact):.1e}")


# ── Example 5 ────────────────────────────────────────
dt = 0.01                                          # s
true_position = [0.2 * i * dt for i in range(6)]   # m, steady 0.2 m/s
noise = [0.0005, -0.0005, 0.0005, -0.0005, 0.0005, -0.0005]   # m
measured = [p + n for p, n in zip(true_position, noise)]

speeds = [(measured[i + 1] - measured[i]) / dt for i in range(5)]
print([round(v, 2) for v in speeds])
