牛顿法
通过 变量 x 的变化速度(导数)来改变x 的调整量,
f(x) = x^2 -N
f(x2) =f(x1) - (x^2 - N)/2*x
Implement
def get_sqrt(v):
count = 10
x = 1
while count > 0:
count -= 1
x -= (x * x - v) / (2 * x)
return x
get_sqrt(5) # 2.23606797749979
泰勒展开式 推导牛顿法公式
CODE
def squareByTaylor(num, precise=2):
'''
根据泰勒展开式计算平方根
precise:正整数
负数返回复数集
'''
appendix = ''
if num == 0:
return 0
if num == -1:
return 'i'
if num < 0:
num = -num
appendix = ' i'
if precise < 0:
precise = 2
result, preresult = 1, 0
while abs(result - preresult) > 0.1 ** precise:
preresult = result
result = (result + num / result) / 2
return str(result) + appendix
二分算法逼近
取中位值进行逼近
def squareByBinary(num, precise=2):
'''
根据二分法逼近答案
precise应该是正整数
负数返回复数集
'''
appendix = ''
if num == 0:
return 0
if num == -1:
return 'i'
if num < 0:
num = -num
appendix = ' i'
if precise < 0:
precise = 2
result, preresult = num/2, 0
while abs(result**2 - num) > 0.1 ** precise:
if result**2 > num:
result = (result + preresult) / 2
elif result**2 < num:
preresult, result = result, (result + num) / 2
return str(result) + appendix