一元二次方程求解python代码
时间: 2024-06-24 15:00:55 浏览: 207
求一元二次方程解-python讲义前3章
在Python中,我们可以使用内置的数学库`math`或第三方库如`numpy`来解一元二次方程。一元二次方程的标准形式是ax^2 + bx + c = 0。以下是使用`cmath`库(当系数可能为复数时)和`numpy`库分别解一元二次方程的简单示例:
1. 使用`cmath`(适用于实数和复数解):
```python
import cmath
def solve_quadratic_equation(a, b, c):
delta = (b**2) - (4*a*c)
if delta > 0:
x1 = (- cmath.sqrt(delta)) / (2*a)
return x1, x2
elif delta == 0:
x = -b / (2*a)
return x, x
else: # 复数根
real_part = -b / (2*a)
imaginary_part = cmath.sqrt(-delta) / (2*a)
return real_part, complex(real_part, imaginary_part)
# 示例
a = 1
b = -3
c = 2
sol = solve_quadratic_equation(a, b, c)
print(f"解: {sol}")
```
2. 使用`numpy`(仅适用于实数解):
```python
import numpy as np
def solve_quadratic_equation_numpy(a, b, c):
discriminant = b**2 - 4*a*c
roots = np.roots([a, b, c])
return roots
# 示例
sol_numpy = solve_quadratic_equation_numpy(1, -3, 2)
print(f"解: {sol_numpy}")
```
阅读全文