Skip to content

Instantly share code, notes, and snippets.

@countlurk
Created October 5, 2016 21:10
Show Gist options
  • Save countlurk/eb653b81cfc5f1801749a47ab8dee797 to your computer and use it in GitHub Desktop.
Save countlurk/eb653b81cfc5f1801749a47ab8dee797 to your computer and use it in GitHub Desktop.
Square Root created by Pawtiko - https://repl.it/DpAW/10
import math
number = eval(input("Enter a postive number: "))
lower = 0
#example: sqrt(0.5) is greater than 0.5
if number <= 1:
upper = number + 1
else:
upper = number
guess = 0
sqrt = 0
done = False
iterations = eval(input("Maximum iterations: "))
required = iterations
while done == False:
if guess**2 == number:
sqrt = guess
done = True
guess = (upper + lower) / 2
if guess**2 < number:
lower = guess
elif guess**2 > number:
upper = guess
iterations -= 1
if iterations == 0:
sqrt = guess
done = True
print(sqrt)
print('Iterations performed:',required - iterations)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment