获得epsilon的准确性
getting the accuracy of epsilon
我正在尝试创建一个函数来计算数字的平方根,而不需要平方根命令。无需任何库即可得到 epsilon 精度的答案,我现在有了基本代码
def mySqrt(b, e) :
sqrt = b**.5
我尝试了很多不同的方法来解决这个问题,但我不知道如何在 epsilon 中实现 e
使用babylonian method求平方根。至于准确性检查,您需要标准的 sqrt
函数,然后计算 (expected-outcome)/expected
作为您的百分比误差。
您可以实施 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 内获取根本身更精确。
我正在尝试创建一个函数来计算数字的平方根,而不需要平方根命令。无需任何库即可得到 epsilon 精度的答案,我现在有了基本代码
def mySqrt(b, e) :
sqrt = b**.5
我尝试了很多不同的方法来解决这个问题,但我不知道如何在 epsilon 中实现 e
使用babylonian method求平方根。至于准确性检查,您需要标准的 sqrt
函数,然后计算 (expected-outcome)/expected
作为您的百分比误差。
您可以实施 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 内获取根本身更精确。