Last active
September 29, 2021 14:44
-
-
Save corehello/37afab6f0d3e91d8346e7a994d84462d to your computer and use it in GitHub Desktop.
sqrt function(concept of proof) in python 3
This file contains 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
def sqrt(n, p): | |
# any number can be writen as n = a*10 +b, where a >=0, b is 0~9 | |
# for example 123 = 12 * 10 + 3 | |
# so then any number N = (a*10 + b)^2 + remainer = a^2*100 + b*(b+20*a) + remainer | |
# then b*(b+20*a) <= N - a^2*100 | |
# then we can calulate max b to match the expression | |
print("sqrt {} with {} precision is:".format(n, p)) | |
if len(n) %2 != 0: | |
n = "0"*(2-len(n)%2) + n | |
splited_n = [n[i:i+2] for i in range(0,len(n),2)] | |
A,B,Remainer,Result = 0,0,0,"" | |
def findb(N, a, b, remainer, result): | |
for j in range(0, 11): | |
c = remainer*100 + int(N) | |
if j*(20*a+j) > c: | |
b = j-1 | |
remainer = c - (20*a+b)*b | |
a = 10*a + b | |
result = "{}{}".format(result, b) | |
break | |
return a,b,remainer,result | |
for i in splited_n: | |
A,B,Remainer,Result = findb(i, A, B, Remainer, Result) | |
if Remainer != 0: | |
Result = "{}.".format(Result) | |
for i in ["00" for i in range(p)]: | |
A,B,Remainer,Result = findb(i, A, B, Remainer, Result) | |
return Result,A,Remainer |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
for example: