function root = newton(x0, func, dfunc, imax, tol)
    % NEWTON Solve for the root using Newton's method
    % Inputs:
    %   x0    - Initial guess
    %   func  - Function handle
    %   dfunc - Derivative function handle
    %   imax  - Maximum iterations
    %   tol   - Tolerance for convergence
    %
    % Output:
    %   root - Estimated root

    x = x0;
    for i = 1:imax
        fval = func(x);
        dval = dfunc(x);
        
        if abs(dval) < 1e-10
            error('Derivative near zero at iteration %d, x = %f.', i, x);
        end
        
        x_new = x - fval / dval;
        fprintf('Iteration %d: x = %.6f, f(x) = %.6f\n', i, x, fval);
        
        if abs(x_new - x) < tol
            root = x_new;
            fprintf('Converged at iteration %d: root = %.6f\n', i, root);
            return;
        end
        
        x = x_new;
    end
    
    error('Maximum iterations reached without convergence.');
end
