为什么计算反三角函数比计算函数本身便宜?

问题描述 投票:0回答:1

长话短说

我在浏览器上运行了以下代码:

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

为什么计算

arc sine
arc cosine
sine
cosine
便宜?

说来话长

我正在编写一个实时模拟,我需要找出两个向量之间的角度以将其与静止角度进行比较。我知道点积给了我余弦,但我不想依赖

acos
,因为据说它非常昂贵。

然后我决定检查一下它有多贵并制定了上面的测试。结果让我感到惊讶,现在我想知道为什么。从我的结果来看,

acos
似乎没那么糟糕。

javascript performance math physics trigonometry
1个回答
0
投票

好吧,我没有注意到代码中的错误。我遵循@knittl的建议并使用了

Math.random
。这表明 @MvG 假设是正确的,因为新结果是:

tan:    0.05559s
atan2:  0.05395s
atan:   0.04782s
acos:   0.04733s
asin:   0.04553s
sin:    0.04376s
cos:    0.04066s
sum:    0.02350s

这些值更有意义。

© www.soinside.com 2019 - 2024. All rights reserved.