Created
November 13, 2013 16:21
-
-
Save caetanus/7451822 to your computer and use it in GitHub Desktop.
Square root by binary search
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
| import sys | |
| def sqrt(n): | |
| low = 0 | |
| high = n | |
| mid = (high - low) / 2. | |
| iter = 0 | |
| while abs((mid ** 2) - float(n)) > 0.00001: | |
| iter += 1 | |
| if (mid ** 2) > n: | |
| high = mid | |
| mid = (high - low) /2. | |
| else: | |
| low = mid | |
| mid = mid + ((high - low) / 2.) | |
| print "iterations", iter | |
| return mid | |
| try: | |
| number = int(sys.argv[1]) | |
| except: | |
| number = 2 | |
| print sqrt(number), number ** 0.5 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment