跳到内容
🛠️ToolsShed

一元二次方程求解器

逐步求解 ax² + bx + c = 0。

输入系数

ax² + bx + c = 0

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

公式

  • 判别式:Δ = b² − 4ac
  • Δ > 0:两个不同的实根
  • Δ = 0:一个重根
  • Δ < 0:两个共轭复数根

关于此工具

二次方程式 ax² + bx + c = 0 是代数学中最基础的问题之一,广泛应用于物理、工程、金融和建筑等各个领域。这个工具能够瞬间求解二次方程,不仅给出最终答案,还提供完整的逐步求解过程,让你清楚地理解如何得到解。

只需输入系数 a、b 和 c,求解器就会计算判别式并应用二次公式,找出实数根和复数根。无论是核对作业、验证项目中的计算,还是复习代数知识,这个工具都能提供清晰、系统的解题过程,帮助你理解其背后的数学原理。

常见问题

代码实现

import cmath

def solve_quadratic(a: float, b: float, c: float):
    """Solve ax^2 + bx + c = 0. Returns two roots (may be complex)."""
    if a == 0:
        if b == 0:
            raise ValueError("Not an equation (a=0, b=0)")
        return (-c / b,)  # linear case
    disc = b**2 - 4*a*c
    sqrt_disc = cmath.sqrt(disc)
    x1 = (-b + sqrt_disc) / (2 * a)
    x2 = (-b - sqrt_disc) / (2 * a)
    return x1, x2

def format_root(r: complex) -> str:
    if r.imag == 0:
        return f"{r.real:.6g}"
    return f"{r.real:.4g} + {r.imag:.4g}i"

# Two real roots: x^2 - 5x + 6 = 0  ->  x = 3, 2
x1, x2 = solve_quadratic(1, -5, 6)
print(format_root(x1), format_root(x2))  # 3   2

# Complex roots: x^2 + 1 = 0  ->  x = ±i
x1, x2 = solve_quadratic(1, 0, 1)
print(format_root(x1), format_root(x2))  # 0 + 1i   0 + -1i

Comments & Feedback

Comments are powered by Giscus. Sign in with GitHub to leave a comment.