值错误:Python 中的数学域错误
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23528618/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Value Error: math domain error in Python
提问by sirius_pain
I'm writing a code to help me solve the Pythagorean theorem in Python. Problem is, I keep getting this one error when I have the code try solving for B.
我正在编写代码来帮助我解决 Python 中的勾股定理。问题是,当我让代码尝试解决 B 时,我不断收到这个错误。
This is the bit that always gives me problems:
这是总是给我带来问题的一点:
bsqr = (int(c) ** 2) - (int(a) ** 2)
b = int(bsqr) / sqrt(bsqr)
I get this error:
我收到此错误:
Traceback (most recent call last):
File "<pyshell#24>", line 1, in <module> pythag()
File "C:\Python34\fact.py", line 156, in pythag
b = int(bsqr) / sqrt(bsqr)
ValueError: math domain error
What is causing this error, and how can I fix it?
是什么导致了这个错误,我该如何解决?
采纳答案by mgilson
It's likely because bsqr
is negative and taking the sqrt of a negative number doesn't work too well.
这可能是因为它bsqr
是负数,并且取负数的 sqrt 效果不佳。
>>> import math
>>> math.sqrt(-1)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: math domain error
Check your algebra/inputs. c
(the hypoteneuse) should alwaysbe bigger than either of the legs (a
and b
)
检查您的代数/输入。 c
(斜边)应始终大于任何一条腿(a
和b
)
Also, side note, you could also get a ZeroDivisionError
if you happen to put in values for a
and c
which are equal (after int
truncates them).
另外,请注意,ZeroDivisionError
如果您碰巧输入了a
和c
相等的值(在int
截断它们之后),您也可以获得 a 。