计算一元二次方程的解python
时间: 2024-12-21 07:21:12 浏览: 3
在Python中,计算一元二次方程的解通常会涉及到二次公式,其形式为ax² + bx + c = 0,其中a、b、c是常数且a≠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,)
else: # 当判别式小于0时,我们得到复数根
real_part = -b / (2 * a)
imaginary_part = cmath.sqrt(-discriminant) / (2 * a)
return (real_part, imaginary_part)
# 示例使用
a = 1
b = -3
c = 2
solution = solve_quadratic_equation(a, b, c)
print(f"方程 {a}x^2 + {b}x + {c} 的解为:", solution)
```
阅读全文