By DeepSource

Pythagorean calculation detected with sub-optimal numerics PTC-W0028


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.


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