Pythonで2進数の対数を計算するにはどうすればよいですか。例えば。私は対数2を使用しているこの方程式を持っています
import math
e = -(t/T)* math.log((t/T)[, 2])
それを知っているのは良いことです
math.log
また、ベースを指定できるオプションの2番目の引数を取ることも知ってい
ます。
In [22]: import math
In [23]: math.log?
Type: builtin_function_or_method
Base Class: <type 'builtin_function_or_method'>
String Form: <built-in function log>
Namespace: Interactive
Docstring:
log(x[, base]) -> the logarithm of x to the given base.
If the base not specified, returns the natural logarithm (base e) of x.
In [25]: math.log(8,2)
Out[25]: 3.0
入力または出力がint
またはであるかによって異なりfloat
ます。
assert 5.392317422778761 == math.log2(42.0)
assert 5.392317422778761 == math.log(42.0, 2.0)
assert 5 == math.frexp(42.0)[1] - 1
assert 5 == (42).bit_length() - 1
math.log2(x)
import math
log2 = math.log(x, 2.0)
log2 = math.log2(x) # python 3.3 or later
math.frexp(x)
浮動小数点数の底 2 の対数の整数部分だけが必要な場合、指数の抽出は非常に効率的です。
log2int_slow = int(math.floor(math.log(x, 2.0))) # these give the
log2int_fast = math.frexp(x)[1] - 1 # same result
Python frexp() は、指数を取得して微調整するC 関数 frexp()を呼び出します。
Python frexp() はタプル (仮数、指数) を返します。指数[1]
部を取得します。
2 のべき乗の整数の場合、指数は予想よりも 1 大きくなります。たとえば、32 は 0.5x2⁶ として格納されます。これは上記を説明してい- 1
ます。0.5x2⁻⁴ として格納されている 1/32 にも機能します。
下限は負の無限大に向かうため、この方法で計算された log₂31 は 5 ではなく 4 です。log₂(1/17) は -4 ではなく -5 です。
x.bit_length()
入力と出力の両方が整数の場合、このネイティブの整数メソッドは非常に効率的です。
log2int_faster = x.bit_length() - 1
- 1
2ⁿ には n+1 ビットが必要だからです。など、非常に大きな整数に対して機能します2**10000
。
下限は負の無限大に向かうため、この方法で計算された log₂31 は 5 ではなく 4 になります。
Python 3.3 以降を使用している場合は、既に log2(x) を計算するための組み込み関数があります。
import math
'finds log base2 of x'
answer = math.log2(x)
古いバージョンの python を使用している場合は、次のようにすることができます
import math
'finds log base2 of x'
answer = math.log(x)/math.log(2)
numpy の使用:
In [1]: import numpy as np
In [2]: np.log2?
Type: function
Base Class: <type 'function'>
String Form: <function log2 at 0x03049030>
Namespace: Interactive
File: c:\python26\lib\site-packages\numpy\lib\ufunclike.py
Definition: np.log2(x, y=None)
Docstring:
Return the base 2 logarithm of the input array, element-wise.
Parameters
----------
x : array_like
Input array.
y : array_like
Optional output array with the same shape as `x`.
Returns
-------
y : ndarray
The logarithm to the base 2 of `x` element-wise.
NaNs are returned where `x` is negative.
See Also
--------
log, log1p, log10
Examples
--------
>>> np.log2([-1, 2, 4])
array([ NaN, 1., 2.])
In [3]: np.log2(8)
Out[3]: 3.0
http://en.wikipedia.org/wiki/Binary_logarithm
def lg(x, tol=1e-13):
res = 0.0
# Integer part
while x<1:
res -= 1
x *= 2
while x>=2:
res += 1
x /= 2
# Fractional part
fp = 1.0
while fp>=tol:
fp /= 2
x *= x
if x >= 2:
x /= 2
res += fp
return res
>>> def log2( x ):
... return math.log( x ) / math.log( 2 )
...
>>> log2( 2 )
1.0
>>> log2( 4 )
2.0
>>> log2( 8 )
3.0
>>> log2( 2.4 )
1.2630344058337937
>>>
log[base A] x = log[base B] x / log[base B] Aであることを忘れないでください。
log
したがって、 (自然対数の場合) とlog10
(基数 10 の対数の場合)しかない場合は、次を使用できます。
myLog2Answer = log10(myInput) / log10(2)