Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Square root
function s(x, y) {
return (y = y/2 || x) * y - x < 1e-9 ? //Check if our approximation multiplied with itself is close enough (within 1e-9) to the input
y : //We're done
s(x, y + x / y) //If we're not close enough, caculate the average of our approximation (which is slightly too high) and the input divided by the approximation (which is slightyl too low)
}
function s(x,y){return(y=y/2||x)*y-x<1e-9?y:s(x,y+x/y)}
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
Version 2, December 2004
Copyright (C) 2011 YOUR_NAME_HERE <YOUR_URL_HERE>
Everyone is permitted to copy and distribute verbatim or modified
copies of this license document, and changing it is allowed as long
as the name is changed.
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. You just DO WHAT THE FUCK YOU WANT TO.
{
"name": "simpleSquareRoot",
"description": "A simple implementation of a square root algorithm.",
"keywords": [
"square",
"root",
"sqrt",
"recursive",
"number"
]
}
<!DOCTYPE html>
<title>Dumb square root</title>
<div>Expected value: <b>Something like 1.41421</b></div>
<div>Actual value: <b id="ret"></b></div>
<script>
// write a small example that shows off the API for your example
// and tests it in one fell swoop.
var myFunction = function s(x,y){return(y=y/2||x)*y-x<1e-9?y:s(x,y+x/y)}
document.getElementById( "ret" ).innerHTML = myFunction(10);
</script>
@neizod

This comment has been minimized.

Copy link

neizod commented Oct 4, 2011

keywords: recursive, number

@Prinzhorn

This comment has been minimized.

Copy link
Owner Author

Prinzhorn commented Oct 4, 2011

I added them.

@FarSeeing

This comment has been minimized.

Copy link

FarSeeing commented Apr 16, 2012

-2 bytes: function s(x,y){return(y=y/2||x)*y-x<1e-9?y:s(x,y+x/y)}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.