Last active
December 11, 2015 09:28
-
-
Save ryasmi/4579976 to your computer and use it in GitHub Desktop.
Approximates the square root of any number. Note that the approximation will be an approximation for numbers that contain a large number of digits. Example use sqrt(16) will return 4.
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
sqrt = (() -> | |
sqrtIter = (guess, x) -> | |
if goodGuess(guess, x) then guess | |
else sqrtIter((guess + x / guess) / 2, x) | |
goodGuess = (guess, x) -> Math.abs(guess * guess - x) / x < 0.0000001 | |
(x) -> sqrtIter(1.0, x) | |
)() |
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
var sqrt = function (value) { | |
// Returns -1 if value is negative or not a number. | |
if (!(value >= 0)) {return undefined; } | |
// Otherwise it approximates the square root. | |
var guess = value / 2.0; | |
var diff = (guess * guess) - value; | |
var n = 1; | |
while ((Math.abs(diff) > 0.00000000000000001) && (n < 1000000)) { | |
guess -= diff / (2.0 * guess); | |
diff = (guess * guess) - value; | |
n += 1; | |
} | |
return guess; | |
}; | |
// Testing code. | |
var testSqrt = function () { | |
var testSqrtValue = function (arg, value, id) { | |
console.log(sqrt(arg) === value ? "Test " + id + " passed." : "Test " + id + " failed."); | |
}; | |
testSqrtValue(16, 4, 1); | |
testSqrtValue(-1, -1, 2); | |
testSqrtValue(0, 0, 3); | |
testSqrtValue(121, 11, 4); | |
testSqrtValue(1.5, 1.224744871391589, 5); | |
testSqrtValue("hello", -1, 6); | |
}; |
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
# Uses the Isaac Newton/Joseph Raphson method to calculate the | |
# square root of a wide range of numbers in reasonable time only. | |
def sqrt(value): | |
assert value > 0, "Value must be more than 0." | |
value = float(value) | |
guess = value / 2.0 | |
diff = guess ** 2 - value | |
n = 1 | |
acc = 0.00000000000000001 | |
while abs(diff) > acc and n < 1000000: | |
guess = guess - diff / (2.0 * guess) | |
diff = guess ** 2 - value | |
n += 1 | |
return "guess = {0} iterations = {1} accuracy = {2}".format(guess, n, acc) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment