Advertisement
jukaukor

highprecision_squareroot.py

Nov 11th, 2018
148
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.76 KB | None | 0 0
  1. # high precision square root
  2. # Newton's method
  3. # Juhani Kaukoranta 11.11.2018
  4.  
  5. import math
  6. from decimal import *
  7. def Newton(x,precision) :
  8. '''high precision square root'''
  9. if x > 0 :
  10. getcontext().prec=precision
  11. x0 = Decimal(1)
  12. for n in range (0,70):
  13. x1 = (x0 + Decimal(x)/x0)/Decimal(2)
  14. x0 = x1
  15. return(x0)
  16. if x == 0 :
  17. return(0)
  18.  
  19. if x < 0 :
  20. print("Only non-negative number has a square root")
  21. a = input("Give non-negative number from which to get square root ")
  22. x = float(a)
  23. if x >= 0 :
  24. precision = int(input("How many digits precision, f.eq 100 "))
  25. print("sqrt(",a,") = ",Newton(x,precision))
  26. else:
  27. print("Only non-negative number has square root")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement