บทนำ
วิธีบาบิโลเนียในการหารากที่สอง 基於หนึ่งในวิธีตัวเลข (Numerical Method) ซึ่งพัฒนามาจากวิธี Newton-Raphson สำหรับแก้สมการไม่เชิงเส้น
แนวคิดง่ายๆ: เริ่มจากค่า x が恣意的 (Arbitrary) และ y เป็น 1 เราสามารถหาค่าประมาณรากถัดไปได้โดยการหาค่าเฉลี่ยของ x และ y แล้วค่า y จะถูกอัปเดตด้วย number / x
อินพุตและเอาต์พุต
Input: ตัวเลข: 65 Output: รากที่สองของ 65 คือ: 8.06226
อัลกอริทึม
sqRoot(number)
Input: ตัวเลขแบบ Real
Output: รากที่สองของตัวเลขที่กำหนด
Begin
x := number
y := 1
precision := 0.000001
while relative error ของ x และ y > precision, do
x := (x + y) / 2
y := number / x
done
return x
End
ตัวอย่างโค้ด (C++)
#include <iostream>
#include <cmath>
using namespace std;
float sqRoot(float number) {
float x = number, y = 1; // ค่าเดาเริ่มต้นเป็น number และ 1
float precision = 0.000001; // ผลลัพธ์ถูกต้องถึง 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