gpt4 book ai didi

javascript - 如何提高 Math.atan() 的准确性?

转载 作者:行者123 更新时间:2023-12-03 07:18:57 26 4
gpt4 key购买 nike

我试图在点的 Angular 之间做一些比较,但很快我遇到了一些奇怪的结果。

在这个例子中,我尝试旋转线条,使它们指向中心,但线条的 Angular 似乎超过了它们应该很快的 Angular 。然后,在中心的正上方和正下方,线条开始指向各种方向 (These values are beyond the mathematical range of atan(x)) .

如何从 Math.atan() 获得准确的结果?有没有其他方法可以进行此计算?

我上传了一个“工作”版本到这个 fiddle : https://jsfiddle.net/0y2p6p3n/ .我在 Chrome 中工作。

html:

  <div id="content">                
</div>

JavaScript:

let points = [];
let amount = 1000;
let width = 300;
let height = 300;

for (let i = 0; i<amount;i++) {
let x = Math.random();
let y = Math.random();
let point = {x, y};
points.push(point);
points[i].tan = Math.atan(0.5 - points[i].y)/(0.5 - points[i].x);
points[i].error = Math.abs(points[i].tan) > 3.14/2 ? true : false;
}
for (let point of points) {
let line = document.createElement("div");
line.classList.add("line");
line.style.marginTop = point.y*height + "px";
line.style.marginLeft = point.x*width + "px";
line.style.transform = "rotateZ(" + ((point.tan*(180/Math.PI))) + "deg)";
point.error == true && line.classList.add("error");

document.getElementById("content").appendChild(line);
}

CSS:

#content {
position: relative;
}
.line {
position: absolute;
height: 1px;
width: 10px;
background-color: black;
}
.error {
background-color: red;
}

最佳答案

您正在使用

points[i].tan = Math.atan(0.5 - points[i].y)/(0.5 - points[i].x);

应该是

points[i].tan = Math.atan( (0.5 - points[i].y)/(0.5 - points[i].x) );

let points = [];
let amount = 1000;
let width = 300;
let height = 300;
for (let i = 0; i<amount;i++) {
let x = Math.random();
let y = Math.random();
let point = {x, y};
points.push(point);
points[i].tan = Math.atan( (0.5 - points[i].y)/(0.5 - points[i].x) );
points[i].error = Math.abs(points[i].tan) > 3.14/2 ? true : false;
}
for (let point of points) {
let line = document.createElement("div");
line.classList.add("line");
line.style.marginTop = point.y*height + "px";
line.style.marginLeft = point.x*width + "px";
line.style.transform = "rotateZ(" + ((point.tan*(180/Math.PI))) + "deg)";
point.error == true && line.classList.add("error");
document.getElementById("content").appendChild(line);
}
#content {
position: relative;
}
.line {
position: absolute;
height: 1px;
width: 10px;
background-color: black;
}
.error {
background-color: red;
}
<div id="content"></div>

关于javascript - 如何提高 Math.atan() 的准确性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41145616/

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