美文网首页
迭代法求平方根

迭代法求平方根

作者: Stroman | 来源:发表于2018-03-31 10:07 被阅读309次

问题

求正整数的平方根。

思路

用迭代法解决此问题。其实本题没啥难理解的,因为有个现成的公式,它是用于迭代的,能求近似平方根,怎么得来的我不知道,但是我知道它好使,暂时对我来说就足够了。这个公式就是x1=(x0+a/x0)/2,a就是最开始的输入值,一开始的x0是a/2,x1就是更接近a的平方根的近似解,然后把x1作为x0再次参与计算又会得到一个更近似x1,如此反复。但是如此反复就无穷无尽了,为了让它有一个最终的结果,你还必须设定一个精度,当x0-x1的绝对值小于某一精度的时候就结束,然后才有输出,为啥要绝对值呢,因为小数的开平方的值比原来的大,此时相减为负。再有一点就是这个迭代法不一定非要是递归的,循环也是一种迭代。

使用

package com.company;

public class Main {

    public static void main(String[] args) {
    // write your code here
        Solution.iteratorSquareRoot(2,4);
    }
}

输出

2的平方根是:1.4142135623746899

Process finished with exit code 0

实现

package com.company;

public class Solution {
    /**
     * 用迭代法对正整数求近似平方根
     * @param number
     * @param accuracy
     */
    static public void iteratorSquareRoot(int number,int accuracy) {
        if (number < 1 || accuracy < 1) {
            System.out.println("输入错误");
            return;
        }
        double threshold = 1;
        int insideAccuracy = accuracy;
        while (insideAccuracy > 0) {
            threshold /= 10;
            insideAccuracy--;
        }
        double x0 = number / 2;
        double x1 = (x0 + number / x0) / 2;
        while (Math.abs(x1 - x0) > threshold) {
            x0 = x1;
            x1 = (x0 + number / x0) / 2;
        }
        System.out.println(number + "的平方根是:" + x1);
    }
}

多谢捧场

如果您觉得我的文章有价值,那么赏脸打赏一个,鄙人感激不尽。不过,不打赏看看也是好的,如果有不对的地方,还请您多多指正。


相关文章

网友评论

      本文标题:迭代法求平方根

      本文链接:https://www.haomeiwen.com/subject/mhcgcftx.html