如何用JavaScript高效查找三维空间中距离目标点最近的坐标点,以及判断该点在线段的哪个位置?

如何用JavaScript高效查找三维空间中距离目标点最近的坐标点,以及判断该点在线段的哪个位置?

本文提供javascript解决方案,高效解决两个三维空间几何问题:一、查找距离目标点最近的坐标点;二、判断目标点在线段的哪个位置。

一、寻找最近坐标点

给定目标点[x, y, z]和一个包含多个三维坐标点的数组,需找到距离目标点最近的坐标点及其索引。 我们采用欧几里得距离计算,并使用reduce方法优化查找效率:

const target = [-11.034364525537594, 1, 24.978631454302235];const arr = [  [-4.167605156499352, 1, 16.43419792128068],  [-13.60939928892453, 1, 28.216932747654095],  [-16.84770058227477, 1, 27.514650539457307]];const nearestPoint = arr.reduce((nearest, point, index) => {  const distanceSquared = point.reduce((sum, coord, i) => sum + Math.pow(coord - target[i], 2), 0);  if (index === 0 || distanceSquared < nearest.distanceSquared) {    return { point, index, distanceSquared };  }  return nearest;}, { distanceSquared: Infinity });console.log("Nearest point:", nearestPoint.point, "Index:", nearestPoint.index);

二、判断点在线段位置

判断三维坐标点是否位于给定线段上,需要运用空间向量中的三点共线判断。 为避免浮点数精度问题,我们使用toFixed方法控制精度:

立即学习“Java免费学习笔记(深入)”;

function isCollinear(p1, p2, p3, precision = 10) {  const fixed = num => parseFloat(num.toFixed(precision));  return fixed((p2[1] - p1[1]) * (p3[0] - p2[0])) === fixed((p3[1] - p2[1]) * (p2[0] - p1[0])) &&         fixed((p2[2] - p1[2]) * (p3[0] - p2[0])) === fixed((p3[2] - p2[2]) * (p2[0] - p1[0])) &&         fixed((p2[2] - p1[2]) * (p3[1] - p2[1])) === fixed((p3[2] - p2[2]) * (p2[1] - p1[1]));}function findSegmentPosition(point, segment) {  if (isCollinear(segment[0], segment[1], point)) {    //Further checks to determine exact position on the segment could be added here if needed (e.g., using dot product).    return "On segment";  }  return "Not on segment";}const segment = [[-5, 0, 10], [5, 0, 20]];const pointOnSegment = [0, 0, 15];const pointOffSegment = [0, 10, 15];console.log(findSegmentPosition(pointOnSegment, segment)); // Output: On segmentconsole.log(findSegmentPosition(pointOffSegment, segment)); // Output: Not on segment

以上代码提供了更清晰、更易于理解的函数,并对精度问题进行了处理,提高了代码的鲁棒性。 isCollinear 函数可以根据需要调整精度参数 precisionfindSegmentPosition 函数目前仅判断点是否在线段上, 可以根据需求扩展,例如计算点在线段上的比例位置等。

以上就是如何用JavaScript高效查找三维空间中距离目标点最近的坐标点,以及判断该点在线段的哪个位置?的详细内容,更多请关注创想鸟其它相关文章!

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1561763.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2025年12月22日 06:48:17
下一篇 2025年12月22日 06:48:23

相关推荐

发表回复

登录后才能评论
关注微信