Generalization of the root algorithm of the Babylonian square to the nth roots

I was looking for root algorithms and came across a Babylonian algorithm. I really like it because it is simple and easy to understand. But the problem is that it only takes square roots when I create a function that can take the root of a number with any power. I'm just trying to take his positive integer.

Here is the function:

double functions::rot(double x, double y) {
    double z = x;
    double w = 1;
    double e = 0.000001; 
    while (z - w > e){
        z = (z + w) / 2;
        w = x / z;
    }
    return z;
}

y is the power. Does anyone have a way to change this algorithm, so y is the root strength? For example, if y = 3, it takes a cubic root.

+4
source share
2 answers

, , w = x / z w = x / z*z, 1/3 (). , Python:

def rot(x, y): # 
    z = x
    w = 1
    e = 0.000001
    while (z - w > e):
        z = ((y - 1) * z + w) / y
        w = x / (z ** (y - 1)) # a ** b is a to the power of b in Python
                               # you might want to use modular exponentiation in C++
                               # (or not if y is double...)
    return z


print(rot(64, 3)) # prints 4
print(rot(59, 6)) # prints 1.9730678338673044

. . , .

+1

. , k, , n, , ; u ( ):

function iroot(k, n)
    k1, u, s := k-1, n, n+1
    while u < s
        u := (u * k1 + n / (u ** k1)) / k
        s := u
    return s

: . iroot , n k .

0

Source: https://habr.com/ru/post/1608169/


All Articles