Cheesy
Cheesy

Reputation: 23

I'm having trouble troubleshooting my function

I'm attempting to make a function that calculates the area of a triangle given the sides. Sometimes it works, but other times it returns 0.0 when it shouldn't or gives an error. My code is:

def triangle3S(s1,s2,s3):
  s = float((s1 + s2 + s3) / 2)
  a = float(sqrt(s * (s-s1) * (s-s2) * (s-s3)))
  print('The area of this triangle is ' + str(a))

triangle3S(float(input('1st side: ')),float(input('2nd side: ')),float(input('3rd side: ')))

The error it sometimes returns is:

Traceback (most recent call last):
  File "main.py", line 23, in <module>
    triangle3S(float(input('1st side: ')),float(input('2nd side: ')),float(input('3rd side: ')))
  File "main.py", line 20, in triangle3S
    a = float(sqrt(s * (s-s1) * (s-s2) * (s-s3)))
ValueError: math domain error

I have sqrt(x) imported and it seems to be working as it should most of the time. I'm wondering why my function is so unreliable and how I can fix it.

Upvotes: 1

Views: 54

Answers (1)

Ran Cohen
Ran Cohen

Reputation: 751

I tried to import sqrt from math, and it's working for me. What are your imports and inputs?

import math

def triangle3S(s1,s2,s3):
    s = float((s1 + s2 + s3) / 2)
    a = float(math.sqrt(s * (s-s1) * (s-s2) * (s-s3)))
    print('The area of this triangle is ' + str(a))

triangle3S(float(input('1st side: ')),float(input('2nd side: ')),float(input('3rd side: ')))

output:

1st side: 1
2nd side: 1
3rd side: 1

The area of this triangle is 0.4330127018922193

the numbers [13, 2, 4] can't be calculated as area calc web

enter image description here

you can use try and except or if else:

def triangle3S(s1,s2,s3):
    try:
        s = float((s1 + s2 + s3) / 2)
        a = float(math.sqrt(s * (s-s1) * (s-s2) * (s-s3)))
        print('The area of this triangle is ' + str(a))
    except:
        print("can't be calculated")

output:

1st side: 13
2nd side: 2
3rd side: 4
can't be calculated

Upvotes: 3

Related Questions