python - 编码二次公式时的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
那么发生了什么?
解决方案
在 Python 中,^
是一个位运算符,称为 XOR(异或)
我想你把它误认为是计算能力。在 python 中,您使用**
.
x ** y
- x 提高到 y 次方
所以像这样修复你的代码
x1 = (-b + sqrt(b**2-(4*a*c)))/(2*a)
推荐阅读
- python - 出现错误“调用 Python 对象时超出最大递归深度”
- timer - STM32 TIM1 内部时钟(CK_INT)
- python - 如果项目的长度为 1 或更少,则从字典中删除项目
- python-3.x - 将 matplotlib 图例标记大小设置为常数
- c# - 如何从 WPF 中的 MainWindow 访问 ChildWindow 文本框
- python - 将输出发送到字典
- c# - Unity Facebook SDK,登录后无法从字典中检索国家
- jquery - Jquery 承诺 whit 对象
- html - Web 组件/HtmlElement:单元测试
- c# - 使用给定的肥皂消息构建 WCF 服务的最佳方法