Babylon algorithm in C ++

Babylon algorithm for calculating the square root of n numbers as follows:

a. a first guess answers GUESS (may be n / 2 as the first answer)

b. Calculate r = n / guess

c.令guess = (guess + r)/2

D. If necessary, return to step 2 is repeated a plurality of times. The more steps 2 and 3 repeated the number, the closer is the square root of n guess.

Writing a program, as an input integer value of n, Babylon algorithm is repeatedly performed until the guess guess the previous error in the range of 1%, a double output as answers.

code show as below:

#include <iostream>

double babi(int n) {

    double guess = n / 2;//以n/2作为第一个答案

    double tmp = guess;//获取第一个答案的值

    while (1)

    {

        double r = n / guess;//计算

        guess = (guess + r) / 2;//通过这两个步骤,得到一个新的值

        if (abs(tmp - guess) < 0.01) {//让第一个答案的值和第二个答案的值比较比较再除于第一个答案的值 < 0.01

            break;

        }

        tmp = guess;//如果不符合if条件,就第二个值赋值给第一个值,再进行判断,知道两个值的差值小于 0.01。

    }

    return tmp;

}

Output screenshots:

 

Guess you like

Origin blog.csdn.net/qq_41979469/article/details/92571516