首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >编码二次公式时的ValueError

编码二次公式时的ValueError
EN

Stack Overflow用户
提问于 2021-08-05 11:20:39
回答 1查看 51关注 0票数 0

我正在用Python编写二次公式。下面的函数用于求解x^2-x-20。如果你做这个数学运算,你会得到-4和5。

代码语言:javascript
复制
# 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)

然而,如果你运行它,你会得到:

代码语言:javascript
复制
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

那么到底是怎么回事呢?

EN

回答 1

Stack Overflow用户

发布于 2021-08-05 11:24:35

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

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

x ** y -x的y次幂

所以像这样修复你的代码

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

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/68665628

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档