0

This is a program for finding if three numbers create a triangle. Granted, there are better ways to do this, and the function gives True when it should, in fact, be False, supposing the goal is for finding a triangle. What's bothering me, however, is that when I input certain numbers, that is, when a = b = c, I should be getting back True, but I don't.

Here is my code:

def is_triangle(a, b, c):
    import math
    cos_c = float(((a**2)+(b**2)-(c**2))) / (2*a*b)
    cos_a = float(((b**2)+(c**2)-(a**2))) / (2*b*c)
    cos_b = float(((c**2)+(a**2)-(b**2))) / (2*c*a)
    if -1<=cos_a<=1 and -1<=cos_b<=1 and -1<=cos_c<=1:
        ang_a = math.acos(cos_a)
        ang_b = math.acos(cos_b)
        ang_c = math.acos(cos_c)
        total = (ang_c + ang_a + ang_b) * (180/math.pi)
        print total
        if total == 180:
            return True
        else:
            return False
    else:
        return False

The print total function is to make sure that the total is, in fact, equal to 180. For example:

if I run the function with:

is_triangle(1,2,2)

I get back total = 180.0 = True. So far so good.

if I run the function with:

is_triangle(1,2,3)

I get back total = 180.0 = True. While for an actual triangle these numbers wouldn't work, it still runs through the function properly.

However, if I run the function with:

is_triangle(2,2,2)

I get back total = 180.0 = False. This is where I'm confused, as I should be getting back True. Why does it give me False?

KHD123
  • 1
  • 1
  • In general, btw, a question title should be as specific to the individual question as possible. "Floating-point comparisons unexpectedly false" would be stronger as a title, simply by virtue of being less general -- more specific to the individual problem and circumstances necessary to cause it. – Charles Duffy Feb 24 '18 at 00:58
  • Thanks for the advice! I'm new here so I'm still learning, so thanks for taking the time. – KHD123 Feb 24 '18 at 01:26

0 Answers0