Skip to content

Instantly share code, notes, and snippets.

@morten-olsen
Created May 4, 2021 09:33
Show Gist options
  • Save morten-olsen/d9b0fc0e7d2d11d03b3e321a92b67e06 to your computer and use it in GitHub Desktop.
Save morten-olsen/d9b0fc0e7d2d11d03b3e321a92b67e06 to your computer and use it in GitHub Desktop.
Sqrt in pure JS
const guess = (x, maxRounds = 1000) => {
let max = x / 2;
let min = 0;
let precision = max - min;
let current;
for (let i = 0; i < maxRounds; i++) {
precision = max - min;
current = (max - min) / 2 + min;
const result = current * current;
if (result === x) {
return [current, i, 0];
}
if (result > x) {
if (max === current) {
return [current, i, precision];
}
max = current;
}
if (result < x) {
if (min === current) {
return [current, i, precision];
}
min = current;
}
}
return [current, -1, precision];
};
const x = 9235345;
const messure = (fn, rounds = 1000000) => {
const start = process.hrtime();
for (let i = 0; i < rounds; i++) {
fn(Math.random() * 100000);
}
return (process.hrtime(start)[1] / 1000000) / rounds;
};
const ownTime = messure(guess);
const buildInTime = messure(Math.sqrt);
const [result, rounds, precision] = guess(x);
console.log(`
Own result: ${result}
Build in result: ${Math.sqrt(x)}
Own time: ${ownTime} ms
Build in time: ${buildInTime} ms
Max diviation: ${precision}
Rounds: ${rounds}
Target: ${x}
Own: ${result * result}
Build in ${Math.sqrt(x) * Math.sqrt(x)}
`);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment