2015-03-31 91 views
2

是什麼導致了這個問題?python數學域錯誤 - 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 
+0

檢查是否總d *(DA)*(DB)的*(dc)是正數,因爲sqrt(-1)是數學中的複數,但不是python – CY5 2015-03-31 18:39:06

+0

而且通常我們會問,當您發佈「爲什麼會出現此錯誤?」時,還會包含導致該錯誤的輸入。 – Teepeemm 2015-04-01 01:52:57

回答

2

的問題是,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" 
+0

謝謝你的回答,只是一個評論:我不能用'del'作爲變量 – szzso24 2015-04-01 08:02:38

+0

噢。這是一個保留字。謝謝 – 2015-04-01 08:05:39

4

sqrt當您嘗試使用負數時會出現該錯誤。 sqrt(-4)給出了該錯誤,因爲結果是複雜數字

對於這一點,你需要cmath

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

我得到了同樣的錯誤我的代碼,直到我用cmath代替math像無水銀說:

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)) 

這種方式運行正常我的代碼。

+0

在另一個使用'cmath'而不是'math'的答案中已經提出了。 – MSeifert 2016-12-21 01:28:01

+0

我必須錯過它。我不打算不給予適當的可信度,而且我也是新的[簡介]來進行疊加。對於不高興的傾向感到抱歉。 – SilverInternet 2016-12-21 03:38:14

0

使用CMATH代替..

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

現在無論數量是否negetive或正你會得到一個結果......

+0

OP正試圖計算一個三角形的面積,似乎不太可能爲一個不明確的三角形返回一個複數值是個好主意。 – 2018-02-18 17:34:14

+0

然後在輸入值之前使用abs()來確保該值爲正值.....然後使用math.sqrt().... – 2018-02-19 05:27:48

+0

這更糟!現在你默默地對問題給出了一個已知的錯誤答案,而不是給出任何錯誤的線索。如果有人詢問邊1,2和5的三角形的面積是多少,則正確的答案不是2.45j,而不是2.45。正確的答案是給消息「沒有這樣的三角形存在」的某種錯誤。 – 2018-02-19 08:36:03