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

หารากของสมการกำลังสอง (Quadratic Equation) - JavaScript

หาค่าราก (Roots) ของสมการกำลังสอง ax² + bx + c = 0 โดยใช้สูตรกำลังสอง

สูตรกำลังสอง

x = (-b ± √(b² - 4ac)) / 2a

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

const coefficients = [3, 12, 2]; // 3x² + 12x + 2 = 0

const findRoots = co => {
  const [a, b, c] = co;
  const discriminant = b * b - 4 * a * c;
  
  if (discriminant < 0) return false; // ไม่มีรากจริง
  
  const d = Math.sqrt(discriminant);
  const x1 = (-b + d) / (2 * a);
  const x2 = (-b - d) / (2 * a);
  return [x1, x2];
};

console.log(findRoots(coefficients));

ผลลัพธ์

[ -0.17425814164944628, -3.825741858350554 ]

กรณีพิเศษ

  • Discriminant > 0: มีรากจริง 2 ค่า
  • Discriminant = 0: มีรากจริง 1 ค่า (Double root)
  • Discriminant < 0: ไม่มีรากจริง (Complex roots)

รองรับ Complex Numbers

const findRootsComplex = ([a, b, c]) => {
  const d = b * b - 4 * a * c;
  const real = -b / (2 * a);
  const imag = Math.sqrt(Math.abs(d)) / (2 * a);
  return d >= 0 
    ? [real + imag, real - imag]
    : [`${real} + ${imag}i`, `${real} - ${imag}i`];
};