Python NumPy log2 – How to make it a negative log?

Question:

I just started working with Numpy because I want to use their log method. I am trying to do -log2(79/859) but can only see how to do log2(74/571) which outputs a negative value when it should be positive. Read the Doc but don’t see how to make it a negative log?

How can I fix this?

print(np.log2(79/859))

Output

-2.947893569733893

Output I want

2.947893569733893

Tried searching through NumPy Docs

Asked By: Steve Smith

||

Answers:

print(-np.log2(74/571))

2.947893569733893

if I correctly understand what you want.

Answered By: MarianD

As I posted in my comment, if you always want a positive value for your logarithm, you can use an absolute value:

np.abs(np.log2(74/571))
# 2.948

Also, as suggested above, you don’t need the NumPy library if you only want to use logarithms. You can accomplish the same with the math standard module and even with built-in functions:

import math

abs(math.log2(74/571))
# 2.948
Answered By: GusSL
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.