Function fixed_sqrt_newton

Source
fn fixed_sqrt_newton<F: FixedPointNumber>(x: &F) -> F
where F::Inner: From<u8>,
Expand description

Approximates the square root of a fixed-point number using the Newton-Raphson method.

This is the core computational primitive for square root operations. The public API is fixed_sqrt, which adds domain checking and exact fast paths before delegating here.

§Algorithm

Newton-Raphson iteration for square roots:

guess_{n+1} = (guess_n + x / guess_n) / 2

Converges quadratically - the number of correct digits roughly doubles each iteration. For fixed-point types, convergence is detected when the change between iterations falls within 2 * ULP, which is the tightest meaningful threshold: the Newton step cannot improve beyond 1 ULP on each side, so tighter tolerances would cause infinite oscillation between adjacent representable values.

Iteration stops early on stagnation (improvement stops or reverses), and is hard-capped at MAX_ITERATIONS to guarantee termination.

§Initial Guess Strategy

Input rangeInitial guessReason
x > 1(x + 1) / 2Midpoint above 1, closer to result
x = 11Exact, no iteration needed
x in (0.25, 1)xAlready a reasonable approximation
x <= 0.250.25Avoids starting too close to zero

§Arguments

  • x - A non-negative fixed-point number to compute the square root of. Caller is responsible for ensuring x >= 0. Negative inputs return zero - use fixed_sqrt for proper domain handling.

§Returns

An approximation of sqrt(x), accurate to within 2 * ULP of the true value for well-behaved inputs.