Created
July 17, 2025 20:38
-
-
Save krisselden/b53a129c9113871da1850cb4b08b3130 to your computer and use it in GitHub Desktop.
newtons method applied to sqrt.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @param {number} k | |
* @returns {number} | |
*/ | |
export function sqrt(k) { | |
if (k < 0) { | |
throw new Error("Cannot compute square root of a negative number"); | |
} | |
if (k === 0 || k === 1) { | |
return k; | |
} | |
// initial guess | |
let x = k > 1 ? k / 2 : 2 * k; | |
let i = 0; | |
while (true) { | |
console.log(`Iteration ${i++}: x = ${x}`); | |
let y = x * x - k; | |
if (Math.abs(y) < 1e-14) { | |
return x; | |
} | |
// 2x is the derivative of x^2 | |
// this is Newton's method for finding roots | |
// x - f(x)/f'(x) = x - (x^2 - k) / (2x) | |
const newX = (k / x + x) / 2; | |
const delta = Math.abs(newX - x); | |
x = newX; | |
// check if we made significant progress | |
if (Math.abs(delta) < 1e-14) { | |
break; | |
} | |
} | |
console.log(`Iteration ${i++}: x = ${x}`); | |
return x; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment