Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/293.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
python数学域错误-sqrt_Python_Math_Dns_Sqrt - Fatal编程技术网

python数学域错误-sqrt

python数学域错误-sqrt,python,math,dns,sqrt,Python,Math,Dns,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

是什么导致了这个问题

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
回溯(最近一次呼叫最后一次):
文件“C:/Python27/fájlok/háromszög terület2.py”,第11行,在
s=sqrt(d*(d-a)*(d-b)*(d-c))
ValueError:数学域错误
问题在于,只有当两个数字之和大于第三个数字时,这个数字才有效。您需要明确地检查这一点

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

如果您想在不使用
的情况下执行此操作,请尝试使用
块,您可以按如下方式执行此操作

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)

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

检查d*(d-a)*(d-b)*(d-c)的总数是否为正数,因为sqrt(-1)在数学中是复数,但在Python中不是。通常,当你发布“我为什么会得到这个错误?”,我们会问这个问题,您还包括导致该错误的输入。谢谢您的回答,只是一个评论:我不能使用'del'作为变量哦,是的。这是一个保留字。ThanksIt已经在另一个答案中被提议使用
cmath
而不是
math
。我肯定错过了它。我无意不给予适当的信任,我也是stackoverflow的新手。很抱歉,这是一种无意义的倾向。OP正在尝试计算三角形的面积,似乎不太可能为指定错误的三角形返回复杂值是一个好主意。然后在输入值之前,使用abs()确保该值为正……然后使用math.sqrt()……这更糟!现在你默默地给出了一个已知的错误答案,而不是给出任何错误的线索。如果有人问边为1、2和5的三角形的面积是多少,正确答案不是2.45j,也不是2.45。正确的答案是给出一个信息“不存在这样的三角形”的错误。嗯……然后首先我们需要检查边满足毕达哥拉斯定理,然后继续。。。
import cmath
num=cmath.sqrt(your_number)
print(num)