
尽管 0.1 + 0.2 在数学上等于 0.3,但在计算机中,由于浮点数精度问题,a 和 b 的值略有不同,导致比较结果为 false。
为了解决浮点数精度问题,可以采用以下方法:
以下代码展示了如何使用Numpy计算线段交点,并处理浮点数精度问题:
import numpy as np
from numpy.core.umath_tests import inner1d
DECIMALS = 6 # 期望精度
def line_intersection(a, b): # a=L1(p1, p2) b=L2(q1, q2)
da = a[1] - a[0]
db = b[1] - b[0]
dc = b[0] - a[0]
x = np.cross(da, db)
x2 = inner1d(x, x)
s = inner1d(np.cross(dc, db), x) / x2
ip = (a[0] + da * s[..., None]).reshape(-1, 3)
valid = np.isfinite(ip).any(axis=-1)
return ip[valid]
def grid(files, rows, cols=0):
if cols == 0:
cols = 1
return np.array(np.meshgrid(np.arange(files),
np.arange(rows),
np.arange(cols))).T.reshape(-1, 3)
def intersection_points(grid):
i1, i2 = np.triu_indices(len(grid), k=1)
points = line_intersection((grid[i1], grid[i2]), (grid[i1, None], grid[i2, None]))
return np.unique(np.round(points, decimals=DECIMALS), axis=0)
grid = grid(3, 3)
with np.errstate(all='ignore'):
intersectionPoints = intersection_points(grid)
print(len(intersectionPoints))
print(intersectionPoints)代码解释:
本文介绍了在Python中计算线段交点时如何处理浮点数精度问题。通过使用Numpy进行向量化计算和精度控制,可以有效地避免由于浮点数运算误差导致的重复交点问题,并确保结果的准确性。在实际应用中,需要根据具体情况选择合适的精度,并处理特殊情况,以获得最佳的计算效果。
以上就是计算线段交点时处理浮点数精度问题的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号