求一元二次方程的解python代码
时间: 2024-09-23 10:16:49 浏览: 196
在Python中,可以使用内置函数`cmath`来求解一元二次方程,公式为 `x = [- 4ac)] / (2a)`,其中 `a`, `b`, `c` 分别是二次方程 `ax² + bx + c = 0` 的系数。这里我们通常需要导入 `math` 库并用到 `sqrt()` 函数来计算平方根。
下面是一个简单的示例代码:
```python
import cmath
def solve_quadratic_equation(a, b, c):
# 计算判别式
discriminant = (b**2) - (4*a*c)
# 根据判别式的值确定解的情况
if discriminant > 0:
root1 = (-b + cmath.sqrt(discriminant)) / (2 * a)
root2 = (-b - cmath.sqrt(discriminant)) / (2 * a)
return root1, root2
elif discriminant == 0:
root = -b / (2 * a)
return root
else: # 复数根(虚根)
real_part = -b / (2 * a)
imaginary_part = cmath.sqrt(-discriminant) / (2 * a)
return complex(real_part, imaginary_part), complex(real_part, -imaginary_part)
# 示例:求解 x^2 + 5x + 6 = 0
coefficients = [1, 5, 6]
solutions = solve_quadratic_equation(*coefficients)
print(f"方程 {coefficients[0]}x^2 + {coefficients[1]}x + {coefficients[2]} 的解为:")
for i, solution in enumerate(solutions, start=1):
print(f"解{f' ({i})' if isinstance(solution, complex) else ''}: {solution}")
阅读全文