Created
July 9, 2017 02:59
-
-
Save akhilcb/2d3f1a026e36d54dfe2793074dd91811 to your computer and use it in GitHub Desktop.
Finding Squareroot of a number without using any maths function(Efficient algorithm)
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
func squareroot(number: Double) -> Double { | |
if number <= 0 { | |
return 0 | |
} | |
var x = number / 3 | |
var y = number / x | |
let maxDiff: Double = 0.0001 | |
while abs(y - x) > maxDiff { | |
x = (x + y) / 2 | |
y = number / x | |
} | |
return x | |
} | |
let squreroot = squareroot(number: 9000000) | |
print("squreroot = ", squreroot) | |
//Output: | |
//squreroot = 3000.00000000004 | |
// while loop is executed only 14 times for a value of 9000000. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment