Skip to content

Square root by Newton's method as a CLI tool

Question

Without calling any library square-root function, write a function that computes a\sqrt{a}, and package it as a command-line program that reads the number from its arguments.

Short answer

Newton iteration xk+1=12(xk+a/xk)x_{k+1}=\tfrac12\left(x_k+a/x_k\right), which converges quadratically. Reject negative input, return 00 for 00, start from a sensible guess (e.g. aa or 11, or scale by powers of 44 first) and stop when the relative change is below tolerance. The program should parse argv, validate that the argument is numeric and print a usage message on bad input.

Adapted from Joshi, Denson & Downes, Quant Job Interview Questions and Answers, Q7.29, p.233; question and answer rewritten by SelfMadeQuant.com.

See the hint and the full worked solution in the question bank (free account).

Open the worked solution

Lessons behind this question