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

# ── Example 1 ────────────────────────────────────────
def bisection(f, a, b, tol):
    """Find a root of f between a and b to within tol."""
    if f(a) * f(b) > 0:
        raise ValueError("f(a) and f(b) must have opposite signs")
    steps = 0
    while b - a > tol:
        mid = (a + b) / 2
        if f(a) * f(mid) <= 0:   # sign change in the left half
            b = mid
        else:                    # sign change in the right half
            a = mid
        steps += 1
    return (a + b) / 2, steps

def f(x):
    return x * x - 2           # its positive root is √2

print(bisection(f, 1.0, 2.0, 1e-6))


# ── Example 2 ────────────────────────────────────────
def bisection(f, a, b, tol):
    if f(a) * f(b) > 0:
        raise ValueError("f(a) and f(b) must have opposite signs")
    steps = 0
    while b - a > tol:
        mid = (a + b) / 2
        if f(a) * f(mid) <= 0:
            b = mid
        else:
            a = mid
        steps += 1
    return (a + b) / 2, steps

def net_torque(w):
    motor = 0.5 * (1 - w / 30)       # N·m, falls to zero at 30 rad/s
    load = 0.05 + 0.0004 * w * w     # N·m, friction plus a drag-like term
    return motor - load

w, steps = bisection(net_torque, 0.0, 30.0, 1e-6)
print(f"{w:.4f} rad/s after {steps} steps, residual {net_torque(w):.1e} N·m")


# ── Example 3 ────────────────────────────────────────
def newton(f, dfdx, x, tol=1e-12, max_steps=50):
    for step in range(1, max_steps + 1):
        x_new = x - f(x) / dfdx(x)
        print(f"step {step}: x = {x_new:.15f}")
        if abs(x_new - x) < tol:
            return x_new
        x = x_new
    raise RuntimeError("Newton's method did not converge")

def f(x):
    return x * x - 2

def dfdx(x):
    return 2 * x

newton(f, dfdx, 1.0)


# ── Example 4 ────────────────────────────────────────
def f(x):
    return x**3 - 2 * x + 2

def dfdx(x):
    return 3 * x**2 - 2

x = 0.0
for step in range(1, 5):
    x = x - f(x) / dfdx(x)
    print(f"step {step}: x = {x}")
