求解一元二次方程方程代码python
时间: 2024-10-03 15:03:13 浏览: 27
在Python中,你可以使用内置的`cmath`模块(对于复数求解)或`math`模块(仅限于实数解)来求解一元二次方程。一元二次方程通常的形式是 ax^2 + bx + c = 0。下面是一个简单的示例,展示如何使用公式法来求解实数解:
```python
import math
def solve_quadratic_equation(a, b, c):
# 计算判别式
discriminant = b**2 - 4*a*c
# 实数解的情况
if discriminant >= 0:
x1 = (-b + math.sqrt(discriminant)) / (2 * a)
x2 = (-b - math.sqrt(discriminant)) / (2 * a)
return x1, x2
# 复数解的情况
else:
real_part = -b / (2 * a)
imaginary_part = math.sqrt(-discriminant) / (2 * a)
return complex(real_part, imaginary_part), complex(real_part, -imaginary_part)
# 示例:求解方程x^2 + 5x + 6 = 0
a = 1
b = 5
c = 6
solutions = solve_quadratic_equation(a, b, c)
print("解为:", solutions)
阅读全文