使用巴比倫方法計算平方根
巴比倫方法用於計算平方根,它以牛頓-拉夫遜方法為基礎,該方法用於解決非線性方程。
其思想很簡單,從 x 的任意值和 y 為 1 開始,我們可以透過找到 x 和 y 的平均值來簡單地獲得下一次近似根。然後,y 值將更新為數字 / x。
輸入和輸出
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
廣告