다항식 방정식 풀이기
1차·2차·3차 다항식 방정식을 단계별로 풀어드립니다.
자주 묻는 질문
코드 구현
import numpy as np
def solve_polynomial(coefficients: list[float]) -> list[complex]:
"""
Solve polynomial given coefficients [a_n, ..., a_1, a_0].
E.g., [1, -3, 2] represents x^2 - 3x + 2
"""
roots = np.roots(coefficients)
return roots.tolist()
# x^2 - 3x + 2 = 0 -> roots: 2.0, 1.0
coeffs = [1, -3, 2]
roots = solve_polynomial(coeffs)
for r in roots:
print(f"x = {r.real:.6f}" if r.imag == 0 else f"x = {r.real:.4f} + {r.imag:.4f}i")
# x^3 - 6x^2 + 11x - 6 = 0 -> roots: 3, 2, 1
coeffs2 = [1, -6, 11, -6]
print(np.roots(coeffs2)) # [3. 2. 1.]Comments & Feedback
Comments are powered by Giscus. Sign in with GitHub to leave a comment.