我试图创建一个找到数字平方根的函数,而不使用平方根命令。这得到了没有任何库的epsilon准确性的答案,我现在有了基本代码
def mySqrt(b, e) :
sqrt = b**.5
我尝试了很多不同的方法,但我无法弄清楚如何在epsilon中实现e
答案 0 :(得分:3)
您可以实现Newton's method,这是一种迭代方法,可以将许多方程解算为任意精度。应用于平方根,递归为
或在Python代码中:
def my_sqrt(a, e):
diff = e + 1 # random diff > e
sqrt = 1.0 # start must not be 0
while diff > e:
sqrt = sqrt - (sqrt * sqrt - a) / (2 * sqrt)
diff = sqrt * sqrt - a
if diff < 0: # make sure diff is positive without calling abs
diff = -1 * diff
return sqrt
>>> my_sqrt(2, 0.00001)
1.4142156862745099
承认,这需要在重新考虑后考虑epsilon。因此,结果实际上比在epsilon中获取根本身更精确。
答案 1 :(得分:-1)
使用babylonian method查找平方根。至于准确性检查,您需要标准的sqrt
函数,然后将(expected-outcome)/expected
计算为百分比误差。