编码二次公式时的值错误

2024-10-02 12:23:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在用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

那么到底发生了什么


Tags: topylinemathsqrtusersfilex1
1条回答
网友
1楼 · 发布于 2024-10-02 12:23:18

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

我想你把它误认为是计算功率。在python中,可以使用**计算功耗

x ** y - x raised to the power y

所以像这样修复代码

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

相关问题 更多 >

    热门问题