javascript - 手动计算对数

标签 javascript math numbers integer logarithm

我想计算mathematical logarithm “用手”...

...哪里代表 logarithmBase代表值。

<小时/>

一些示例(请参阅 Log calculator ):

The base 2 logarithm of 10 is 3.3219280949

The base 5 logarithm of 15 is 1.6826061945

...
<小时/>

Hoever - 我不想使用已经实现的函数调用,例如 Math.ceil, Math.log, Math.abs, ... ,因为我想要一个干净的 native 解决方案,只处理 +-*/和一些循环。

这是我到目前为止得到的代码:

function myLog(base, x)  {
  let result = 0;
  do {
    x /= base;
    result ++;
  } while (x >= base)
  return result;
}

let x = 10,
    base = 2;

let result = myLog(base, x)
console.log(result)

但上面的方法似乎不是计算以 N 为底的对数的正确方法 - 因此,任何有关如何修复此代码的帮助将不胜感激。

提前一百万谢谢乔纳斯。

最佳答案

您可以使用递归方法:

 const log = (base, n, depth = 20, curr = 64, precision = curr / 2) => 
   depth  <= 0 || base ** curr === n 
      ? curr
      : log(base, n, depth - 1, base ** curr > n ? curr - precision : curr + precision, precision / 2);

可用作:

log(2, 4) // 2
log(2, 10) // 3.32196044921875

您可以通过更改深度来影响精度,并且可以使用curr更改接受值的范围(当前约为180)

<小时/>

它是如何工作的:

如果我们已经达到了想要的深度或者我们已经找到了准确的值:

 depth  <= 0 || base ** curr === n 

然后它只返回 curr 并完成。否则它会检查我们想要查找的对数是否低于或高于当前的对数:

         base ** curr > n

然后它将继续递归地搜索值 1) 将深度降低一 2) 按当前精度增加/减少 curr 3)精度较低

<小时/>

如果您讨厌函数式编程,这里有一个命令式版本:

  function log(base, n, depth = 20) {
   let curr = 64, precision = curr / 2;
   while(depth-- > 0 && base ** curr !== n) {
     if(base ** curr > n) {
       curr -= precision;
     } else {
       curr += precision;
     }
     precision /= 2;
    }
    return curr;
  }

顺便说一下,我用的算法叫"logarithmic search"通常称为“二分查找”。

关于javascript - 手动计算对数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50335506/

相关文章:

javascript - 如何在网页上保持 SignalR 连接?

python - 如何对 CSV 文件中的多列进行分组和求和?

list - 如何在 Haskell 中使用两个数字创建一个列表?

javascript - 从 json 代码中删除 javascript 对象变量名称文本

javascript - 当某些输入发生更改时触发 ajax 请求

javascript - 浮点: Can I recursively divide/multiple numbers by 2 and never get rounding errors?

algorithm - 使用堆排序可以排序的元素数量?

c# - 从一段曲面点中找到圆心

php - 在 PHP 中从数组(Lat Long)获取数字

Java:将数字分成相等的部分或彼此近似