# How to square root a variable?

#1

How do you calculate the square root of a variable?
I know to use `import math` but when I put a variable that is a result of an equation such as `math.sqrt(total)` it says that it is a math domain error.
Help appreciated.

It is not an an exercise of codecademy, i did it myself.
here is the code:

``````from time import sleep
import math
print "Heron's Formula calculator!"
side1 = int(raw_input("Input side length: "))
side2 = int(raw_input("Input second side length: "))
side3 = int(raw_input("Input third side length: "))
S = side1 / 2. + side2 / 2 + side3 / 2
print "The semi perimeter is " + str(S) + " cm."
total = S - side1 * S - side2 * S - side3 * S
total2 = total * S
print math.sqrt(total2)
``````

#2

can you please post the full code you ran which produced an error?

#3

A math domain error will occur if we attempt to take the square root of a negative number. You may need to refactor your math a little of uncover the cause.

``````============ RESTART: D:/cc/discuss/users/uraveragecoder/heron.py ============
Heron's Formula calculator!
Input side length: 3
Input second side length: 4
Input third side length: 5
The semi perimeter is 6.0 cm.
Traceback (most recent call last):
File "D:/cc/discuss/users/uraveragecoder/heron.py", line 12, in <module>
print (math.sqrt(total2))
ValueError: math domain error
>>> side1, side2, side3
(3, 4, 5)
>>>
``````

From your code I was able to derive the following refactored (and simplified) version:

(Python 3; change `input` to `raw_input` for Python 2)

``````from math import sqrt
print ("Heron's Formula calculator")
a = int(input("a side length: "))
b = int(input("b side length: "))
c = int(input("c side length: "))
s = (a + b + c) / 2                                        # 2 * s == a + b + c
print ("The semi-perimeter is, {:.1f} units.".format(s))
area_squared = (s - a) * (s - b) * (s - c) * s
print ("The triangle area is,  {:.1f} square-units".format(sqrt(area_squared)))
``````
``````============ RESTART: D:/cc/discuss/users/uraveragecoder/heron.py ============
Heron's Formula calculator
a side length: 3
b side length: 4
c side length: 5
The semi-perimeter is, 6.0 units.
The triangle area is,  6.0 square-units
>>>
``````

Recall that by order of operations, subtraction follows multiplication. Grouping is needed in the above to switch the order.

``````total = (S - side1) * (S - side2) * (S - side3) * S
``````

Edit

For Python 2, write this line as followsâ€¦

``s = float(a + b + c) / 2``

#4

Thank you very much. I thought I was using the math function wrong but it was my math that was wrong.

#5

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.