sqrt
to calculate hypotenuse may cause OverflowError
2
3
4def side_height(length, breadth):
5 value = sqrt(length**2 + breadth**2) 6 return value
7 print("The side height is", value)
8
Calculating the length of the hypotenuse using the standard formula c = sqrt(a**2 + b**2)
may lead to overflow if the two other sides are both very large.
Even though c
will not be much bigger than max(a, b)
, either a**2
or b**2
(or both) could be. Thus, the calculation could overflow, even though the result is well within representable range.
It is recommended to use the built-in function hypot(a,b)
from the math
library.
Example:
from math import sqrt, hypot
a = 3e154 # a^2 > 1e308
b = 4e154 # b^2 > 1e308
# with these, c = a^2 + b^2 = 5e154 which is less than 1e308
def hypotenuseDirect():
return sqrt(a**2 + b**2) # This will give an `OverflowError`
def hypotenuseBuiltin():
return hypot(a, b) # This will give the expected result, without overflowing