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

วิธีคำนวณรากที่ n (nth Root) ของตัวเลขใน JavaScript

เพื่อคำนวณรากที่ n ใช้ Math.pow() ร่วมกับ Math.abs() สูตร: x^(1/n)

ตัวอย่างฟังก์ชันคำนวณราก

<html>
  <head>
    <title>Calculate root</title>
  </head>
  <body>
    <script>
      function displayRoot(x, num) {
        var val = num % 2;
        if ((val == 1) || x < 0) x = -x;
        var a = Math.pow(x, 1 / num);
        var numCheck = Math.pow(a, num);
        if (Math.abs(x - numCheck) < 1 && (x > 0 === numCheck > 0))
          return val ? -a : a;
      }
      document.write(displayRoot(36, 2) + "<br>");   // 6
      document.write(displayRoot(49, 2) + "<br>");   // 7
      document.write(displayRoot(36, -2) + "<br>");  // 1/6
      document.write(displayRoot(216, -2) + "<br>"); // 1/14.7
    </script>
  </body>
</html>

วิธีง่ายกว่า (Modern)

// รากที่ n ของ x
function nthRoot(x, n) {
  if (n === 0) throw new Error("Root cannot be zero");
  if (x < 0 && n % 2 === 0) return NaN; // รากคู่ของติดลบ = NaN
  return Math.sign(x) * Math.pow(Math.abs(x), 1 / n);
}

console.log(nthRoot(27, 3));   // 3
console.log(nthRoot(16, 4));   // 2
console.log(nthRoot(-8, 3));   // -2
console.log(nthRoot(2, 2));    // 1.414... (sqrt(2))

กรณีพิเศษ

  • Math.sqrt(x) – รากที่ 2 (square root) ใช้สำหรับ n=2
  • Math.cbrt(x) – รากที่ 3 (cube root) ใช้สำหรับ n=3
  • รากคู่ของเลขติดลบ = NaN (ใน Real numbers)