python 数学域错误 - sqrt

python math domain error - sqrt

导致问题的原因是什么?

from math import sqrt
print "a : "
a = float(raw_input())
print "b : "
b = float(raw_input())
print "c : "
c = float(raw_input())
d = (a + b + c)/2
s = sqrt(d*(d-a)*(d-b)*(d-c))
print "a+b+c =", a, b, c
print "Distr. =", d*2, "Area =", s

错误:

Traceback (most recent call last):
   File "C:/Python27/fájlok/háromszög terület2.py", line 11, in <module>
       s = sqrt(d*(d-a)*(d-b)*(d-c))
ValueError: math domain error

问题是 Heron's formula 只有当两个数之和大于第三个数时才有效。您需要明确检查。

在使用代码时,更好的方法是使用 异常处理

try:
    s = sqrt(d*(d-a)*(d-b)*(d-c))
    print "a+b+c =", a, b, c
    print "Distr. =", d*2, "Area =", s
except ValueError:
    print "Please enter 3 valid sides"

如果你想在没有 try 块的情况下这样做,你可以这样做

delta = (d*(d-a)*(d-b)*(d-c))
if delta>0:
    s = sqrt(delta)
    print "a+b+c =", a, b, c
    print "Distr. =", d*2, "Area =", s
else:
    print "Please enter 3 valid sides"

sqrt 当您尝试将它与负数一起使用时会出现该错误。 sqrt(-4) 给出该错误,因为结果是 复数

为此,您需要 cmath:

>>> from cmath import sqrt
>>> sqrt(-4)
2j
>>> sqrt(4)
(2+0j)

在我使用 cmath 而不是 math 之前,我的代码出现了同样的错误,就像 aneroid 说的那样:

import sys
import random
import cmath

x = random.randint(1, 100)
y = random.randint(1, 100)

a = 2 * x * cmath.sqrt(1 - x * 2 - y * 2)
b = 2 * cmath.sqrt(1 - x * 2 - y * 2)
c = 1 - 2 * (x * 2 + y * 2)

print ( 'The point on the sphere is: ', (a, b, c) )

这样 运行 我的代码正确。

改用 cmath..

import cmath
num=cmath.sqrt(your_number)
print(num)

现在不管数字是负数还是正数你都会得到一个结果...