Calculate angle of triangle Python
43,748
Solution 1
It's a little more compicated than that. You need to use the law of cosines
>>> A = 7
>>> B = 7
>>> C = 9.899
>>> from math import acos, degrees
>>> degrees(acos((A * A + B * B - C * C)/(2.0 * A * B)))
89.99594878743945
This is accurate to 4 significant figures. If you provide a more precise value of C, you get a more accurate result.
>>> C=9.899494936611665
>>> degrees(acos((A * A + B * B - C * C)/(2.0 * A * B)))
90.0
Solution 2
You can use this also.
print(str(int(round(math.degrees(math.atan2(x,y)))))+'°')
This accepts two inputs as two heights of the triangle and you can get the output angle in proper degree format.
Author by
Shannon Hochkins
Passionate about learning new things, constantly working on my own projects to achieve that goal.
Updated on July 12, 2022Comments
-
Shannon Hochkins almost 2 years
I'm trying to find out the angle of the triangle in the following, I know it should be 90 degrees, however I don't know how to actually calculate it in the following:
Here's what I've tried:
angle = math.cos(7/9.899) angleToDegrees = math.degrees(angle) returns: 43.XX
What am I doing wrong?
-
Shannon Hochkins over 10 yearsThis just gave me an even 45.00
-
Shannon Hochkins over 10 yearsis that not what math.degrees does? converting radians to degrees/angles
-
Shannon Hochkins over 10 yearsThat worked great, you wouldn't mind explaining it a bit more though would you?
-
John La Rooy over 10 years@ShannonHochkins, follow the link to wikipedia for the explanation. It's really off-topic for this site.
-
Shannon Hochkins over 10 yearsWhy is it off topic? I asked how to calculate this, usually an answer is best when it has better descriptions rather than just the code.
-
John La Rooy over 10 years@ShannonHochkins, because it's math. You could try asking for an explanation on math.stackexchange.com
-
Teepeemm over 10 yearsTrig functions are for when you have an angle of 90 degrees, and you're interested in some other angle.
-
Teepeemm over 10 yearsIt does convert radians to degrees. But tan(1) is not radians to begin with. The fact that you are treating it as radians is wrong.
-
TehTris over 10 years@Teepeemm trig funcs are for all triangles, they are just simpler when a 90deg angle is involved.
-
Teepeemm about 5 yearsThis code assumes that OP's marked angle is 90degrees, and then gives the acute angle next to input "BC".