Phương pháp Babylon để tìm căn bậc hai dựa trên một trong những phương pháp số, dựa trên phương pháp Newton-Raphson để giải các phương trình phi tuyến tính.
Ý tưởng rất đơn giản, bắt đầu từ một giá trị tùy ý của x, và y là 1, chúng ta có thể đơn giản nhận được ước lượng gần đúng tiếp theo của căn bằng cách tìm giá trị trung bình của x và y. Sau đó, giá trị y sẽ được cập nhật với số / x.
Đầu vào và Đầu ra
Input: A number: 65 Output: The square root of 65 is: 8.06226
Thuật toán
sqRoot(number)
Đầu vào: Con số thực.
Đầu ra: Căn bậc hai của một số đã cho.
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
Ví dụ
#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);
} Đầu ra
Enter Number to find square root: 65 The square root of 65 is: 8.06226