当前位置:   article > 正文

接一元二次方程的几种解法,用python代码实现_python一元二次方程求解代码

python一元二次方程求解代码

一元二次方程的解法有以下几种:公式法、因式分解法、配方法、求根公式法。

下面是使用Python代码实现一元二次方程的解法:

1. 公式法:

```python
import math

def solve_quadratic_equation(a, b, c):
    delta = b**2 - 4*a*c
    if delta < 0:
        return "无实根"
    elif delta == 0:
        x = -b / (2*a)
        return x
    else:
        x1 = (-b + math.sqrt(delta)) / (2*a)
        x2 = (-b - math.sqrt(delta)) / (2*a)
        return x1, x2

# 示例
a = 1
b = -3
c = 2
result = solve_quadratic_equation(a, b, c)
print(result)
```

2. 因式分解法:

```python
def solve_quadratic_equation(a, b, c):
    if a == 0:
        return "不是二次方程"
    if b == 0:
        x = 0
        if -c/a >= 0:
            return x, math.sqrt(-c/a)
        else:
            return "无实根"
    if c == 0:
        x1 = 0
        x2 = -b/a
        return x1, x2
    delta = b**2 - 4*a*c
    if delta < 0:
        return "无实根"
    elif delta == 0:
        x = -b / (2*a)
        return x
    else:
        x1 = (-b + math.sqrt(delta)) / (2*a)
        x2 = (-b - math.sqrt(delta)) / (2*a)
        return x1, x2

# 示例
a = 1
b = -3
c = 2
result = solve_quadratic_equation(a, b, c)
print(result)
```

3. 配方法:

```python
def solve_quadratic_equation(a, b, c):
    if a == 0:
        return "不是二次方程"
    if b == 0:
        x = 0
        if -c/a >= 0:
            return x, math.sqrt(-c/a)
        else:
            return "无实根"
    if c == 0:
        x1 = 0
        x2 = -b/a
        return x1, x2
    delta = b**2 - 4*a*c
    if delta < 0:
        return "无实根"
    elif delta == 0:
        x = -b / (2*a)
        return x
    else:
        x1 = (-b + math.sqrt(delta)) / (2*a)
        x2 = (-b - math.sqrt(delta)) / (2*a)
        return x1, x2

# 示例
a = 1
b = -3
c = 2
result = solve_quadratic_equation(a, b, c)
print(result)
```

4. 求根公式法:

```python
def solve_quadratic_equation(a, b, c):
    if a == 0:
        return "不是二次方程"
    if b == 0:
        x = 0
        if -c/a >= 0:
            return x, math.sqrt(-c/a)
        else:
            return "无实根"
    if c == 0:
        x1 = 0
        x2 = -b/a
        return x1, x2
    delta = b**2 - 4*a*c
    if delta < 0:
        return "无实根"
    elif delta == 0:
        x = -b / (2*a)
        return x
    else:
        x1 = (-b + math.sqrt(delta)) / (2*a)
        x2 = (-b - math.sqrt(delta)) / (2*a)
        return x1, x2

# 示例
a = 1
b = -3
c = 2
result = solve_quadratic_equation(a, b, c)
print(result)
```

以上是四种常见的一元二次方程解法的Python代码实现。根据输入的系数a、b、c,可以得到方程的解或者无解的提示。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/盐析白兔/article/detail/481206
推荐阅读
相关标签
  

闽ICP备14008679号