m2skills

squareroot python

Apr 18th, 2017
159
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.39 KB | None | 0 0
  1. # program to find square root of a integer number without using square root function
  2. import time
  3. def squareRoot(number,sqroot):
  4.    
  5.     # setting answer to be accurate upto 6 decimal places
  6.     # change this to get more accuracy
  7.     error = 0.000001
  8.    
  9.     # calculating num
  10.     num = number/sqroot
  11.     # till the difference is greater than error keep taking average
  12.     while abs(num-sqroot) > error:
  13.         sqroot = (sqroot+num)/2
  14.         num = number/sqroot
  15.         print(sqroot)
  16.         print(num)
  17.         # if num and sqroot are equal then we directly print the answer
  18.         if num == sqroot:
  19.             break
  20.            
  21.     print("The Square Root of " + str(number) + " is " + str(sqroot))
  22.     return
  23.    
  24. # main function
  25. cont = True
  26. while(cont):
  27.    
  28.     number = float(input("Enter the number whose square root is to be found : "))
  29.    
  30.     #if the number is less than 0 then ask user to enter another number
  31.     while number < 0:
  32.         print("Enter a number greater than 0")
  33.         number = int(input("Enter the number whose square root is to be found : "))
  34.    
  35.     # if the number is 0 or 1 then the answer is also is also 0 or 1
  36.     if number == 0 or number == 1:
  37.         print("The Square Root of " + str(number) + " is " + str(number))
  38.    
  39.     # else take initial guess from the user
  40.     else:
  41.         sqroot = int(input("Enter the initial guess : "))
  42.         sqroot = sqroot%number
  43.         squareRoot(number,sqroot)
  44.        
  45.     n = int(input("Do you want to enter another number (1/0): "))
  46.     if n == 0:
  47.         cont = False
Add Comment
Please, Sign In to add comment