gpt4 book ai didi

javascript - 几何 - 计算点到线的距离

转载 作者:行者123 更新时间:2023-11-30 08:35:48 32 4
gpt4 key购买 nike

我想计算一个点到由 2 个点定义的直线的距离。

我正在使用 javascript,这就是我使用维基百科得出的结论:https://en.wikipedia.org/wiki/Distance_from_a_point_to_a_line

function distance(point1, point2, x0, y0) {
return ((Math.abs((point2.y - point1.y) * x0 -
(point2.x - point1.x) * y0 +
point2.x * point1.y -
point2.y * point1.x)) /
(Math.pow((Math.pow(point2.y - point1.y, 2) +
Math.pow(point2.x - point1.x, 2)),
0.5)));
}

问题是它似乎不准确,因为如果我输入这些参数:

alert(distance({ x: 1, y: 1 }, { x: 2, y: 2 }, 1, 0));

它返回 1/sqrt(2) 而不是返回 1(这是点 (1, 0)(1, 1)

点处的线

编辑:我明白上面的代码没有做我想做的事。它从一个点计算到一条由 2 点表示的线,但该线是无限的(我想要更像是具有 2 个端点的向量的东西)

我找到了答案 here

最佳答案

我认为 1/sqrt(2) = 0.7071... 非常正确。见图片:enter image description here

编辑:

var board = JXG.JSXGraph.initBoard('jxgbox', {
boundingbox: [-1, 3, 3, 0],
keepaspectratio: true,
axis: true
});

var f1 = function(x) {
return x;
};

board.create('functiongraph', [f1]);

board.create('point', [1, 1], {
size: 4,
name: '1,1'
});
board.create('point', [2, 2], {
size: 4,
name: '2,2'
});
var p1 = board.create('point', [1, 0], {
size: 4,
name: '1,0'
});
var p2 = board.create('point', [0.5, 0.5], {
size: 0,
name: '1,0'
});
var li2 = board.create('line', [p1, p2], {
straightFirst: false,
straightLast: false,
strokeWidth: 2,
dash: 2
});
<html>

<head>
<link rel="stylesheet" type="text/css" href="http://jsxgraph.uni-bayreuth.de/distrib/jsxgraph.css" />
<script type="text/javascript" src="http://jsxgraph.uni-bayreuth.de/distrib/jsxgraphcore.js"></script>
</head>

<body>
<div id="jxgbox" class="jxgbox" style="width:500px; height:600px;"></div>
</body>

</html>

关于javascript - 几何 - 计算点到线的距离,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31494662/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com