log2 in python math module

风格不统一 提交于 2020-01-22 08:16:12

问题


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.


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/2993214/log2-in-python-math-module

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!