Python中的二次方程

时间:2019-12-28 13:51:48

标签: python math

我一直试图在python中求解二次方程,但是数学模块显示数学域错误。代码看起来像这样-

import math


def solve(a, b, c, choice):
    if choice == '+':
        x12 = (-b + math.sqrt((pow(b, 2) - 4 * a * c))) / 2 * a
    if choice == '-':
        x12 = (-b - math.sqrt((pow(b, 2) - 4 * a * c))) / 2 * a

    return x12


x = float(input("Enter coefficient of x^2->"))
y = float(input("Enter coefficient of x->"))
z = float(input("Enter value of c->"))

print("Which root to find?")
choice = input("+ or -")

print(solve(x, y, z, choice))

显示的错误:

Traceback (most recent call last):
  File "/home/sheldon/Desktop/PythonProjects/Physics/quadraticEquation.py", line 21, in <module>
    print(solve(x, y, z, choice))
  File "/home/sheldon/Desktop/PythonProjects/Physics/quadraticEquation.py", line 9, in solve
    x12 = (-b + math.sqrt((pow(b, 2) - 4 * a * c))) / 2 * a
ValueError: math domain error

0 个答案:

没有答案