Войдите в базу 2 в python



Как я должен вычислить журнал для базы два в python. Например. У меня есть это уравнение, где я использую log base 2



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

10 ответов:

это хорошо, чтобы знать, что

alt text

но также знаю, что math.log принимает необязательный второй аргумент, который позволяет указать основание:

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

float in-float out

import math

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

float in-int out

если все, что вам нужно, это целая часть базы журнала 2 числа с плавающей запятой,math.frexp() может быть довольно эффективным:

log2int_slow = int(math.floor(math.log(x, 2.0)))
log2int_fast = math.frexp(x)[1] - 1
  • Python frexp () вызывает C функция frexp () который просто захватывает и настраивает показатель.

  • Python frexp () возвращает кортеж (мантисса, экспонента). Так что [1] возвращает экспоненту часть. Для интегральных степеней 2 показатель степени на один больше, чем можно было бы ожидать. Например, 32 хранится в виде 0.5x2⁶. Это объясняет - 1 выше. Также работает для 1/32, который хранится как 0. 5x2 -⁴.


int in-int out

если вход и выход являются целыми числами, то целочисленный метод .bit_length() может быть даже более эффективным:

log2int_faster = x.bit_length() - 1
  • - 1 потому что 2 requires требует n+1 бит. Это единственный вариант, который работает для очень больших целых чисел, например,2**10000.

  • все версии инт-выхода будут пол журнал к отрицательной бесконечности, поэтому журнал₂31 4 Не 5.

Если вы находитесь на python 3.4 или выше, то он уже имеет встроенную функцию для вычисления 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
>>> 

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

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

попробуйте это ,

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

не забывай об этом журнал[базы] х = журнал[основания] х / журнала[основание B] а.

Так что если у вас есть только log (для натурального логарифма) и log10 (для журнала base-10), вы можете использовать

myLog2Answer = log10(myInput) / log10(2)

Comments

    Ничего не найдено.