2010-09-15 7 views
73

Come si calcola il log in base due in python. Per esempio. Ho questa equazione in cui sto usando logaritmo in base 2Accedere alla base 2 in python

import math 
e = -(t/T)* math.log((t/T)[, 2]) 
+2

Quello che devi dovrebbero funzionare se si prende le parentesi quadre intorno al ", 2" nella chiamata 'math.log()'. L'hai provato? – martineau

+3

nice entropy calculation –

+0

math.log (value, base) –

risposta

157

E 'bene sapere che

alt text

ma anche sapere che math.log accetta un secondo argomento opzionale che consente di specificare la base:

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 
+4

+1. Formula del cambio di base FTW –

+2

Argomento 'base' aggiunto nella versione 2.3, btw. –

+3

Che cos'è questo? sintassi? Non riesco a trovare riferimenti per questo. – wap26

1

log_base_2 (x) = log (x)/log (2)

2

logbase2 (x) = log (x)/log (2)

5
>>> 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 
>>> 
+0

Questo è incorporato nella funzione 'math.log'. Vedi la risposta di unutbu. – tgray

+0

Hai ragione, non lo sapevo - grazie;) – puzz

0

non dimenticate che log [base A] x = log [base B] x/log [base B] A.

Quindi, se avete solo log (per logaritmo naturale) e log10 (per la base-10 log), è possibile utilizzare

myLog2Answer = log10(myInput)/log10(2) 
7

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 
+0

Punti extra per un algoritmo che può essere adattato per fornire sempre la parte intera corretta, diversamente da int (math.log (x, 2)) – user12861

9

Utilizzando 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 
9

Se siete su Python 3.4 o superiore allora ha già una funzione built-in per il calcolo log2 (x)

import math 
'finds log base2 of x' 
answer = math.log2(x) 

Se si utilizza una versione precedente di python, è possibile eseguire questa operazione

import math 
'finds log base2 of x' 
answer = math.log(x)/math.log(2) 
27

galleggiante - galleggiante out

import math 

log2 = math.log(x, 2.0) 
log2 = math.log2(x) # python 3.4 or later 

galleggiante - int out

Se tutto ciò che serve è la parte intera del logaritmo in base 2 di un numero in virgola mobile, math.frexp() potrebbe essere piuttosto efficiente:

log2int_slow = int(math.floor(math.log(x, 2.0))) 
log2int_fast = math.frexp(x)[1] - 1 
  • Python frexp() chiama lo C function frexp() che cattura e modifica l'esponente.

  • Python frexp() restituisce una tupla (mantissa, esponente). Quindi [1] ottiene la parte esponente. Per i poteri integrali di 2 l'esponente è uno più di quanto ci si potrebbe aspettare. Ad esempio 32 è memorizzato come 0.5x2⁶. Questo spiega lo - 1 sopra. Funziona anche per 1/32 che viene memorizzato come 0.5x2⁻⁴.


int in - int out

Se sia all'ingresso che all'uscita sono interi, il metodo intero .bit_length() potrebbe essere ancora più efficiente:

log2int_faster = x.bit_length() - 1 
  • - 1 perché 2ⁿ richiede n + 1 bit. Questa è l'unica opzione che funziona per interi molto grandi, ad es. 2**10000.

  • Tutte le versioni int-output sarà piano il registro verso l'infinito negativo, in modo log₂31 è 4 non 5.

+1

Interessante. Quindi stai sottraendo 1 lì perché la mantissa è nell'intervallo [0.5, 1.0)? Darei a questo un paio di voti in più se potessi. – LarsH

+1

Esattamente a destra @LarsH. 32 è memorizzato come 0.5x2⁶, quindi se vuoi log₂32 = 5 devi ** sottrarre 1 **. Vale anche per 1/32, che viene memorizzato come 0.5x2⁻⁴. –

0

Prova questo,

import math 
print(math.log(8,2)) # math.log(number,base)