c语言巴比伦算法,平方根的巴比伦方法

原标题:平方根的巴比伦方法

算法:

此方法可以从(但早于)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返回搜狐,查看更多

责任编辑:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值