提问人:Matheus C 提问时间:8/10/2023 最后编辑:evolutionxboxMatheus C 更新时间:8/11/2023 访问量:57
为什么计算反三角函数比计算函数本身便宜?
Why computing inverse trigonometric functions is cheaper than computing the functions themselves?
问:
长话短说
我在浏览器上运行了以下代码:
function test(f) {
const start = performance.now();
for (let i = 0; i < 1000000; i++) {
f(i);
}
const end = performance.now();
return (end - start) / 1000;
}
function bigTest() {
let cosResults = [];
let acosResults = [];
let sinResults = [];
let asinResults = [];
let tanResults = [];
let atanResults = [];
let atan2Results = [];
let sumResults = [];
for (let i = 0; i < 50; i++) {
cosResults.push(test(Math.cos));
acosResults.push(test(Math.acos));
sinResults.push(test(Math.sin));
asinResults.push(test(Math.asin));
tanResults.push(test(Math.tan));
atanResults.push(test(Math.atan));
atan2Results.push(test((a) => Math.atan2(a, a)));
sumResults.push(test((a) => a + 2 * a));
}
return {
cos: cosResults.reduce((a, b) => a + b, 0) / 50,
acos: acosResults.reduce((a, b) => a + b, 0) / 50,
sin: sinResults.reduce((a, b) => a + b, 0) / 50,
asin: asinResults.reduce((a, b) => a + b, 0) / 50,
tan: tanResults.reduce((a, b) => a + b, 0) / 50,
atan: atanResults.reduce((a, b) => a + b, 0) / 50,
atan2: atan2Results.reduce((a, b) => a + b, 0) / 50,
sum: sumResults.reduce((a, b) => a + b, 0) / 50
};
}
console.log(bigTest());
这是我得到的结果:
tan: 0.02815s
atan2: 0.02225s
cos: 0.01768s
sin: 0.01767s
atan: 0.01137s
acos: 0.00717s
asin: 0.00662s
sum: 0.00401s
为什么计算 and 比 和 便宜?arc sine
arc cosine
sine
cosine
说来话长
我正在编写一个实时模拟,我需要找出两个向量之间的角度,以便将其与静止角度进行比较。我知道点积给了我余弦,但我不想依赖它,因为它据说非常昂贵。acos
然后我决定检查一下它有多贵,并制定了上面的测试。结果让我大吃一惊,现在我想知道为什么。从我的结果来看,似乎并没有那么糟糕。acos
答: 暂无答案
评论
f(i/1000000.0)
Math.random()