牛顿法平方根迭代

时间:2014-04-26 06:21:16

标签: c# algorithm time-complexity square-root newtons-method

我从http://blog.shay.co/newtons-method/提取了此代码:

//a - the number to square root
//times - the number of iterations
public double Sqrt(double a, int times)
{
    if (a < 0)
        throw new Exception("Can not sqrt a negative number");
    double x = 1;
    while (times-- > 0)
        x = x / 2 + a / (2 * x);
    return x;
}

对于数字的迭代次数(如果存在),有什么好的经验法则?(例如,“使用n / 2次迭代”。)

2 个答案:

答案 0 :(得分:5)

  

对于数字的迭代次数(如果存在),有什么好的经验法则?

牛顿方法具有二次收敛性,即。在算法的每一步,答案中的有效位数加倍。因此,该算法在O(log D)时间内计算平方根达到精度的D位数。因此,循环中的迭代次数将取决于预期的准确性。因此,要对结果的准确性进行精细控制,可以在代码中添加一个检查,当估计值不在误差范围之外时,它会返回答案。

public double Sqrt(double a){
    if (a < 0)
        throw new Exception("Can not sqrt a negative number");
    double error = 0.00001;
    double x = 1;
    while (true){
        double val = x*x;
        if(abs(val-a) <= error)
             return x;
        x = x / 2 + a / (2 * x);
    }
}

答案 1 :(得分:0)

如果你想要一个固定迭代次数的保证相对准确度,那么通过将a除以4直到结果在1/2和2之间来准备迭代。或者如果从小于的值开始,则乘以1.记住分区数,因为

  

SQRT(A)= 2 ^ K * SQRT(4 ^( - K)* A)

需要将结果乘以相同数量的因子2.然后,简化a的平方根的相对误差将会下降

  

3 *(1/6)^(2 ^ M)

m次迭代后,或更快,根据

  

(x [m] -sqrt(a))/(x [m] + sqrt(a))=((1-sqrt(a))/(1 + sqrt(a)))^(2 ^米)

通过使用C数学库中浮点指数frexpldexp的访问函数,可以最快地提取和操作4和2所需的幂,Double类中的类似方法在Java。

相关问题