วิธีบาบิโลนในการหารากที่สองนั้นใช้วิธีการเชิงตัวเลขวิธีใดวิธีหนึ่ง ซึ่งใช้วิธีการของนิวตัน- ราฟสันในการแก้สมการไม่เชิงเส้น
แนวคิดนี้ง่าย โดยเริ่มจากค่า 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