值错误: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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 03:05:18  来源:igfitidea点击:

Value Error: math domain error in Python

pythonmathpython-idlesqrt

提问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 bsqris 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 (aand b)

检查您的代数/输入。 c(斜边)应始终大于任何一条腿(ab



Also, side note, you could also get a ZeroDivisionErrorif you happen to put in values for aand cwhich are equal (after inttruncates them).

另外,请注意,ZeroDivisionError如果您碰巧输入了ac相等的值(在int截断它们之后),您也可以获得 a 。

回答by jithin

Please go through this:

请通过这个:

Square roots in python

python中的平方根

Also see the cmathmodule in Python

另请参阅Python 中的cmath模块

cmath module - sqrt

cmath 模块 - sqrt