Algorithm for finding the square root of a number

 

python:

Coding = UTF- # . 8 
from  decimal Import a Decimal
 from  decimal Import getContext 

# 8 is set to show significant digits 
getContext (). prec = . 8 
# 6 find the square root of 
X = 6 

X = a Decimal (STR (X)) 
A = X / a Decimal ( " 2 " ) 
the diff = 0 

the while ( . 1 ): 
    B = (A + X / A) / a Decimal ( " 2 " ) 
    the diff = A- B 
    A = B
     IF (the diff <a Decimal ( "0.001")):
        break

print(a)

Export

2.4494898

 

 

c:

#include <stdio.h>
 int main () {
     // find the square root of 6 
    int X = 6 ; 
    
    a float A = X / 2.0 ;
     a float the diff = 0.0 ;
     a float B = 0.0 ;
     the while ( . 1 ) { 
        B = (A + X / A) / 2.0 ; 
        the diff = A- B; 
        A = B;
         IF (the diff < from 0.001 ) {
             BREAK ; 
        } 
    } 
    the printf ( " square root of% f \ n",a);
    return 0;
}

Export

Is the square root of 2. 449.49 thousand

 

 

reference:

https://www.jianshu.com/p/b31f078994f0

https://blog.csdn.net/qq_16676375/article/details/82909145

https://jingyan.baidu.com/article/f79b7cb31082079144023ebb.html 

 

Guess you like

Origin www.cnblogs.com/sea-stream/p/11323766.html