首页 > 解决方案 > 编码二次公式时的ValueError

问题描述

我正在用 Python 编写二次公式。以下函数应该解决 x^2-x-20。如果你做数学,你会得到 -4 和 5。

# Quadratic Formula
from math import sqrt
def findsolutions(a, b, c):
    """
    Find solutions to quadratic equations.
    """
    x1 = (-b + sqrt(b^2-4*a*c))/(2*a)
    x2 = (-b - sqrt(b^2-4*a*c))/(2*a)
    return x1, x2

x1, x2 = findsolutions(1,-1,-20)
print("The solutions to x^2-x-20 are", x1, "and", x2)

但是,如果你运行它,你会得到:

Traceback (most recent call last):
  File "C:/Users/Atharv 2020/Desktop/Python/1. Quadratic Formula.py", line 11, in <module>
    x1, x2 = findsolutions(1,-1,-20)
  File "C:/Users/Atharv 2020/Desktop/Python/1. Quadratic Formula.py", line 7, in findsolutions
    x1 = (-b + sqrt(b^2-4*a*c))/(2*a)
ValueError: math domain error

那么发生了什么?

标签: pythonvalueerror

解决方案


在 Python 中,^是一个位运算符,称为 XOR(异或)

我想你把它误认为是计算能力。在 python 中,您使用**.

x ** y- x 提高到 y 次方

所以像这样修复你的代码

x1 = (-b + sqrt(b**2-(4*a*c)))/(2*a)


推荐阅读