巴比伦方法求平方根


巴比伦求平方根的方法基于一种数值方法,该方法基于牛顿-拉夫森法求解非线性方程。

这个想法很简单,从 x 的任意值和 y 为 1 开始,我们只需通过求 x 和 y 的平均值来得到根的下一个近似值。然后用  数字 / x 更新 y 值。

输入和输出

Input:
A number: 65
Output:
The square root of 65 is: 8.06226

算法

sqRoot(number)

输入: 实数。

输出: 给定数的平方根。

Begin
   x := number
   y := 1
   precision := 0.000001
   while relative error of x and y > precision, do
      x := (x+y) / 2
      y := number / x
   done
   return x
End

示例

#include<iostream>
#include<cmath>
using namespace std;

float sqRoot(float number) {
   float x = number, y = 1;              //initial guess as number and 1
   float precision = 0.000001;           //the result is correct upto 0.000001

   while(abs(x - y)/abs(x) > precision) {
      x = (x + y)/2;
      y = number/x;
   }
   return x;
}

int main() {
   int n;
   cout << "Enter Number to find square root: "; cin >> n;
   cout << "The square root of " << n <<" is: " << sqRoot(n);
}

输出

Enter Number to find square root: 65
The square root of 65 is: 8.06226


更新日期: 17-Jun-2020

4K+ 浏览量

开启你的 职业生涯

完成课程,获得认证

开始吧
广告
© . All rights reserved.