Reputation: 9
I'm trying to make a calculator in Python but I'm getting and error with the Cosine Rule I have put in.
This is what I have
x = float(input("First Side "))
y = float(input("Second Side "))
z = float(input("Angle which isn't opposite First or Second Side "))
print (" ")
print ("Side is: "+str(math.sqrt(((x**2)+(y**2))-(2*x*y*(math.cos(z)*(180/math.pi))))))
And this is my error
Traceback (most recent call last):
File "D:/Users/---------/Python/test calc.py", line 339, in <module>
print ("Side is: "+str(math.sqrt(((x**2)+(y**2))-(2*x*y*(math.cos(z)*(180/math.pi))))))
ValueError: math domain error
You work out the Cosine Rule by doing this:
a=√(b^2+c^2−2*b*c*cos(α))
In what I've done
x=b
y=c
z=α
Upvotes: 1
Views: 454
Reputation: 2742
It seems math.cos(z)*(180/math.pi) is the part mistaken, making what's inside the math.sqrt
negative for some cases.
print ("Side is: "+str(math.sqrt(((x**2)+(y**2))-(2*x*y*math.cos(z)))))
or math.cos(z*math.pi/180)
will be what you want.
(EDIT: Corrected the upside-down fraction. Thanks: andrew cooke))
Upvotes: 1
Reputation: 46872
in the line
2*x*y*(math.cos(z)*(180/math.pi))
you seem to be trying to convert from degrees to radians? but (1) the factor is upside down and (2) it needs to be inside the cos(...)
.
so you may have meant
2*x*y*math.cos(z*math.pi/180)
(check: when z is 180 degrees, the code above gives pi radians).
Upvotes: 2
Reputation: 6221
It works for me; I'd imagine that you are putting in numbers that are impossible for a triangle. Try your input in a regular calculator and see if it works.
Also, note that your angle needs to be in radians (or you need to convert it to degrees).
I tried sides of 3, 4 and 3.14/2 (approximately 90 degrees in radians) and got 4.99, which approximates the correct answer of 5.
Upvotes: 2