原标题:平方根的巴比伦方法
算法:
此方法可以从(但早于)Newton-Raphson方法导出。
1以任意正起始值x开始(越靠近
根,越多越好)。
2初始化y = 1。
3.执行以下操作直到达到所需的近似值。
a)使用x和y的平均值获得根的下一个近似值
b)设置y = n / x
执行:
C
Java的
Python 3
C#
PHP
filter_none
编辑
play_arrow
brightness_4
#include
/*Returns the square root of n. Note that the function */
float squareRoot(float n)
{
/*We are using n itself as initial approximation
This can definitely be improved */
float x = n;
float y = 1;
float e = 0.000001; /* e decides the accuracy level*/
while(x - y > e)
{
x = (x + y)/2;
y = n/x;
}
return x;
}
/* Driver program to test above function*/
int main()
{
int n = 50;
printf ("Square root of %d is %f", n, squareRoot(n));
getchar();
}
输出:
50的平方根是7.071068
例:
n = 4 / * n本身用于初始近似* /
初始化x = 4,y = 1
下一个逼近x =(x + y)/ 2(= 2.500000),
y = n / x(= 1.600000)
下一个逼近x = 2.050000,
y = 1.951220
下一个逼近x = 2.000610,
y = 1.999390
下一个逼近x = 2.000000,
y = 2.000000
现在终止为(x - y)> e。
如果我们确定n是一个完美的正方形,那么我们可以使用以下方法。对于非完美平方数,该方法可以进入无限循环。例如,对于3,下面的while循环将永远不会终止。
C ++
C
Java的
Python3
C#
PHP
filter_none
编辑
play_arrow
brightness_4
// C++ program for Babylonian
// method for square root
#include
using namespace std;
class gfg
{
/*Returns the square root of n.
Note that the function */
public:
float squareRoot(float n)
{
/*We are using n itself as initial approximation
This can definitely be improved */
float x = n;
float y = 1;
/* e decides the accuracy level*/
float e = 0.000001;
while(x - y > e)
{
x = (x + y) / 2;
y = n / x;
}
return x;
}
};
/* Driver code*/
int main()
{
gfg g;
int n = 49;
cout << "Square root of " << n <<
" is " << g.squareRoot(n);
getchar();
}
// This code is contributed by SoM15242
输出: 49的根是7返回搜狐,查看更多
责任编辑: