求一元二次方程 ax²+bx+c =0的根python
时间: 2024-10-06 10:06:25 浏览: 78
在Python中,我们可以使用math库或者数值计算库如numpy来求解一元二次方程ax² + bx + c = 0的根。这里我将展示如何使用`cmath`库,因为它支持复数解:
```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, root
else: # 当判别式小于0,有两个共轭复数根
real_part = -b / (2 * a)
imaginary_part = cmath.sqrt(-discriminant) / (2 * a)
root1 = complex(real_part, imaginary_part)
root2 = complex(real_part, -imaginary_part)
return root1, root2
# 使用示例
a, b, c = 1, -3, 2
root1, root2 = solve_quadratic_equation(a, b, c)
print(f"一元二次方程 {a}x^2 + {b}x + {c} 的根是 {root1} 和 {root2}")
阅读全文