def my_sqrt(n):
approx = n/2
closer = (approx + n/approx)/2
while closer != approx:
approx = closer
closer = (approx + n/approx)/2
return approx
I'm a novice coder but I'll give it a go and wiser contributors than me can add to it.
def my_sqrt(n): # create a function calling in an 'n' arguement
approx = n/2 # set a variable equal to 'n' ÷ 2
closer = (approx + n/approx)/2 # set a variable equal to ('approx' variable + 'n' ÷'approx' variable) ÷ 2
while closer != approx: # start of while loop that is run when following 'approx' variable is false, or not equal to
approx = closer # 'approx' variable equals 'closer' variable
closer = (approx + n/approx)/2 # takes the 'closer' variable equal to ('approx' variable + 'n' ÷'approx' variable) ÷ 2
return approx # function returns 'approx' variable
Add this line to see some results in terminal:
print('\'approx\' variable is:', approx)
Add this line indented (under 'closer =' in while loop) and inline with 'def' to see different results.
You'll have to remove this line that is inline with 'def'. It causes an error which I mention just for you to see it.
The programs gives the square root of any number you call the function with (replace a number for 'n').
So if you open Python Idle, paste this code, save, press F5, and type 'my_sqrt(9)' is the python window that opens, you should see some lines with the final line showing a floating point value of 3.0
Replace '9' with any # you want.
Phil
