C# 计算对数基数 2
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13654499/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Calculating Log base 2
提问by FSm
Let we have the following code
让我们有以下代码
(float)Math.Log(3.83031869)
The output i got is
我得到的输出是
1.342948
But when i calculated the Log2 for same number using many online calculators I got
但是当我使用许多在线计算器计算相同数字的 Log2 时,我得到了
1.93746
Could any explanation for this problem please ? Thanks in advance.
请问这个问题有什么解释吗?提前致谢。
采纳答案by JG in SD
Math.Log(num)returns the log of base e
Math.Log(num)返回以 e 为底的对数
Math.Log(num, base)is probably what you are looking for.
Math.Log(num, base)可能是您正在寻找的。
回答by Itay Karo
As can be seen in MSDN http://msdn.microsoft.com/en-us/library/x80ywz41.aspx
在 MSDN http://msdn.microsoft.com/en-us/library/x80ywz41.aspx 中可以看到
The Math.Logfunction computes the log with base e.
该Math.Log函数使用 base 计算日志e。
See http://msdn.microsoft.com/en-us/library/hd50b6h5.aspxfor what you need.
请参阅http://msdn.microsoft.com/en-us/library/hd50b6h5.aspx了解您需要的内容。
回答by Chris Dunaway
When calling the Log method with only a single argument, you get the Log base e. If you provide the second argument of 2.0, you get the result you expect:
当仅使用单个参数调用 Log 方法时,您将获得 Log 基数 e。如果您提供 2.0 的第二个参数,则会得到您期望的结果:
//Testing in LinqPad
void Main()
{
Math.Log(3.83031869).Dump();
Math.Log(3.83031869, 2.0).Dump();
}
Results
结果
1.34294800860817
1.93746443219072
回答by Papayaved
For integer values:
对于整数值:
public static int Log2(UInt64 value) {
int i;
for (i = -1; value != 0; i++)
value >>= 1;
return (i == -1) ? 0 : i;
}

