使用次优数值的勾股定理计算¶
ID: py/pythagorean
Kind: problem
Security severity:
Severity: warning
Precision: medium
Tags:
- accuracy
Query suites:
- python-security-and-quality.qls
使用标准公式 c = sqrt(a**2 + b**2)
计算斜边长度可能会导致溢出,如果另外两条边都非常大。即使 c
不会比 max(a, b)
大很多,但 a**2
或 b**2
(或两者)都会很大。因此,即使结果在可表示范围内,计算也可能会溢出。
建议¶
不要使用 sqrt(a**2 + b**2)
,而是使用 math
库中的内置函数 hypot(a,b)
。
示例¶
以下代码展示了两种不同的斜边计算方法。第一种是勾股定理的直接重写,第二种使用了内置函数。
# We know that a^2 + b^2 = c^2, and wish to use this to compute c
from math import sqrt, hypot
a = 3e154 # a^2 > 1e308
b = 4e154 # b^2 > 1e308
# with these, c = 5e154 which is less that 1e308
def longSideDirect():
return sqrt(a**2 + b**2) # this will overflow
def longSideBuiltin():
return hypot(a, b) # better to use built-in function