Tomasz Ksepka - 2 years ago 65
Python Question

# Law of cosines returns 90 degrees for all angles in a triangle?

I'm working on an assignment where I make a class called Triangle that takes in three sides and returns information about the triangle. Specifically, I am trying to calculate the three angles within the triangle, but for some reason I am getting 90 degrees for all angles, which is impossible. I have gone over my code tons of times but can't find the mistake and would greatly appreciate some help. Thank you.

``````from math import acos, degrees, sqrt
import turtle

class Triangle:

def __init__(self, side_a=None, side_b=None, side_c=None):

self.side_a = side_a
self.side_b = side_b
self.side_c = side_c

def is_triangle(self):
return ((self.side_a + self.side_b) > self.side_c) \
and ((self.side_a + self.side_c) > self.side_b) \
and ((self.side_b +self.side_c) > self.side_a)

def perimeter(self):
if self.is_triangle():
return self.side_a + self.side_b + self.side_c
else:
return None

def area(self):
if self.is_triangle():
s = self.perimeter()/2
print s
return sqrt((s*(s-self.side_a)*(s-self.side_b)*(s-self.side_c)))
else:
return None

def a_angle(self):
if self.is_triangle():
return degrees(acos((self.side_b**2 + self.side_c**2 - self.side_a**2)/(2*self.side_b*self.side_c)))
else:
return None

def b_angle(self):
if self.is_triangle():
return degrees(acos((self.side_c**2 + self.side_a**2 - self.side_b**2)/(2*self.side_c*self.side_a)))
else:
return None

def c_angle(self):
if self.is_triangle():
return degrees(acos((self.side_a**2 + self.side_b**2 - self.side_c**2)/(2*self.side_a*self.side_b)))
else:
return None

def angle(self):
return self.a_angle(), self.b_angle(), self.c_angle()

def __str__(self):
pass

tri = Triangle(11, 7, 9)
print tri.is_triangle()
print tri.perimeter()
print tri.area()
print tri.a_angle()
print tri.b_angle()
print tri.c_angle()
print tri.angle()
``````

Answer Source

In Python 2, division of integers by default truncates the result to an integer, so something like `5/2` will equal 2. In your case, dividing the sides results in zero.

The simplest way to fix it is to do `from __future__ import division` at the very beginning of your file. This makes division always return a float.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download