python数学域错误计算三角形的第三个角度

时间:2017-08-03 14:55:35

标签: python-3.x

这是我的代码,当给出两边和一个角度时计算三角形的第三边。角度的输入应该是度,但是因为math.cos()取弧度的值所以我们需要转换它

import math
a = float(input("enter value for side 1:"))
b = float(input("enter value for side 2:"))
c = float(input("enter angle value in degrees:"))
e = math.radians(c)
g = (a * a) + (b * b)
d = math.sqrt(g - (2 * a * c * (math.cos(e))))
print("third side value", d)

我收到以下错误:

Traceback (most recent call last):
  File "C:/Users/User/PycharmProjects/untitled/question3.py", line 7, in <module>
    d = math.sqrt( g - (2 * a * c * (math.cos(e))))
ValueError: math domain error

任何整改?

1 个答案:

答案 0 :(得分:0)

您使用的是错误的公式。 Cosines规则要求side_a^2 + side_b^2 - 2 * side_a * side_b * cos(angle)你有side_a^2 + side_b^2 - 2 * side_a * angle_in_degrees * cos(angle_in_radians)

您收到错误,因为g - (2 * a * c * (math.cos(e)))可能是(并且是)负数。 math.sqrt仅接受正面论点。