Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

หารากที่สองโดยไม่ใช้ Math.sqrt() ใน JavaScript

วิธี Newton-Raphson (Babylonian Method)

ใช้สูตรซ้ำ: x_{n+1} = (x_n + S/x_n) / 2 โดย S = ตัวเลขที่ต้องการหาราก

ซ้ำจนกว่า |x² - S| < tolerance

โค้ดตัวอย่าง

const squareRoot = (num, precision = 0) => {
  if (num <= 0) return 0;
  
  let res = 1; // ค่าเริ่มต้น
  const deviation = 1 / (10 ** precision); // ความแม่นยำ
  
  // Newton-Raphson iteration
  while (Math.abs(num - (res ** 2)) > deviation) {
    res -= ((res ** 2) - num) / (2 * res);
    // เทียบเท่า: res = (res + num / res) / 2
  }
  
  // ปัดเศษตาม precision
  return Math.round(res * (10 ** precision)) / (10 ** precision);
};

console.log(squareRoot(16));       // 4
console.log(squareRoot(161, 3));   // 12.689
console.log(squareRoot(1611, 4));  // 40.1373

ผลลัพธ์

4 12.689 40.1373

วิธีอื่นๆ

1. Binary Search (Integer Square Root)

const sqrtBinary = (num) => {
  if (num < 2) return num;
  let left = 1, right = Math.floor(num / 2);
  while (left <= right) {
    const mid = Math.floor((left + right) / 2);
    const sq = mid * mid;
    if (sq === num) return mid;
    if (sq < num) left = mid + 1;
    else right = mid - 1;
  }
  return right; // Floor square root
};

2. ใช้ Exponentiation (ES7)

const sqrtExp = (num) => num ** 0.5;
// หรือ
const sqrtExp2 = (num) => Math.pow(num, 0.5);

4. Fast Inverse Square Root (Quake III Algorithm)

// สำหรับ floating point - ใช้ในเกม/กราฟิก
const fastInvSqrt = (num) => {
  const buffer = new ArrayBuffer(4);
  const view = new DataView(buffer);
  view.setFloat32(0, num);
  let i = view.getInt32(0);
  i = 0x5f3759df - (i >> 1);
  view.setInt32(0, i);
  let y = view.getFloat32(0);
  y = y * (1.5 - 0.5 * num * y * y); // Newton iteration
  return 1 / y;
};

ความแม่นยำและประสิทธิภาพ

MethodPrecisionSpeedUse Case
Math.sqrt()High (Hardware)FastestGeneral purpose
Newton-RaphsonConfigurableFastNo Math.sqrt, arbitrary precision
Binary SearchInteger onlyMediumInteger sqrt, embedded systems
** 0.5HighFastModern JS, concise

สรุป

  • Newton-Raphson 收斂เร็วมาก (Quadratic convergence)
  • ค่าเริ่มต้น 1 ใช้ได้ดี สำหรับตัวเลขใหญ่มากควรเริ่มจาก num/2
  • precision parameter ควบคุมจุดหยุดการวนซ้ำ