编写一个一元二次方程python代码
时间: 2024-10-15 10:19:49 浏览: 22
基于python实现的检验一元二次方程是否有实数根的程序
在Python中,你可以编写一个函数来解决一元二次方程,通常形式为`ax^2 + bx + c = 0`。这里有一个简单的例子,它使用了`cmath`模块来处理复数解的情况:
```python
import cmath
def solve_quadratic_equation(a, b, c):
# 计算判别式
discriminant = (b**2) - (4*a*c)
# 求解公式
if discriminant > 0:
x1 = (-b + cmath.sqrt(discriminant)) / (2 * a)
x2 = (-b - cmath.sqrt(discriminant)) / (2 * a)
return x1, x2
elif discriminant == 0:
root = -b / (2 * a)
return (root, root)
else: # 复数根
real_part = -b / (2 * a)
imaginary_part = cmath.sqrt(-discriminant) / (2 * a)
complex_root1 = complex(real_part, imaginary_part)
complex_root2 = complex(real_part, -imaginary_part)
return complex_root1, complex_root2
# 示例
a = 1
b = -3
c = 2
solution = solve_quadratic_equation(a, b, c)
print(f"方程 {a}x^2 + {b}x + {c} 的解为:{solution}")
阅读全文