Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

log2 in python math module

Tags:

python

math

why doesn't it exist?

import math [x for x in dir(math) if 'log' in x] >>> ['log', 'log10', 'log1p'] 

I know I can do log(x,2), but log2 is really common, so I'm kind of baffled.

Oh, it looks like it's only defined in C99, not C90, I guess that answers my question. Still seems kind of silly.

like image 357
nick maxwell Avatar asked Jun 07 '10 21:06

nick maxwell


People also ask

How do you write log2 in Python?

log2(a) : This function is used to compute the logarithm base 2 of a. Displays more accurate result than log(a,2). Syntax : math. log2(a) Parameters : a : The numeric value Return Value : Returns logarithm base 2 of a Exceptions : Raises ValueError if a negative no. is passed as argument.

What is math log2 in Python?

The math. log2() method returns the base-2 logarithm of a number.

What does log2 mean in math?

Log2 Calculation The log base 2, also known as the binary logarithm uses the number 2 as the base. The log2 of a number n is the power to which the number 2 must be raised to obtain the value n. For example, the binary logarithm of 1 is 0, 2 is 1, 8 is 3 and 32 is 5.

What is the log2 function?

The log2() function returns the base-2 logarithm of a number.


2 Answers

I think you've answered your own question. :-) There's no log2(x) because you can do log(x, 2). As The Zen of Python (PEP 20) says, "There should be one-- and preferably only one --obvious way to do it."

That said, log2 was considered in Issue3366 (scroll down to the last 3 messages) which added several other C99 math functions to the math module for Python 2.7 and 3.2.

Edit: log2 was reconsidered in Issue11888 and added in Python 3.3.

like image 158
Daniel Stutzbach Avatar answered Oct 05 '22 07:10

Daniel Stutzbach


I'm not sure that there is that you want, but:

-- From math point of view you can do for example math.log(x)/math.log(2).

-- If input X has an integral type and you are waiting for the integral rounded result - you can do it rather faster with right shifting. This works with SHR command and without Taylor series + local interpolation, which is under the hood of libc log() calls.

like image 39
Konstantin Burlachenko Avatar answered Oct 05 '22 08:10

Konstantin Burlachenko