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

Why computing inverse trigonometric functions is cheaper than computing the functions themselves?

提问人:Matheus C 提问时间:8/10/2023 最后编辑:evolutionxboxMatheus C 更新时间:8/11/2023 访问量:57

问:

长话短说

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

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 sinearc cosinesinecosine

说来话长

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

然后我决定检查一下它有多贵,并制定了上面的测试。结果让我大吃一惊,现在我想知道为什么。从我的结果来看,似乎并没有那么糟糕。acos

JavaScript 性能 数学 物理 三角函数

评论

3赞 MvG 8/10/2023
当我阅读代码时,您正在将 0 到 999999 的整数传递给您的函数。其中大多数都在 acos 的领域之外,因此在单次比较后,该函数可以很早地返回 NaN。不过,这个论点并不能解释 atan 的性能。
1赞 knittl 8/10/2023
@MvG 听起来像是一个合理的假设。如果调用更改为或使用 0 到 1 () 之间随机生成的数字,会发生什么情况?f(i/1000000.0)Math.random()

答: 暂无答案