Home > Software engineering >  Python NumPy log2 - How to make it a negative log?
Python NumPy log2 - How to make it a negative log?

Time:12-02

I just started working with Numpy because I want to use their log method. I am trying to do -log2(74/571) 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(74/571))

Output

-2.947893569733893

Output I want

2.947893569733893

Tried searching through NumPy Docs

CodePudding user response:

You can use the absolute value function if that's what you mean.

But your impression of the log2(x) function is incorrect. Here is a plot.

Note that log2(1) = 0.0. If x < 1, then log2(x) < 0. Fractions will have negative logarithms. The function is undefined for x < 0.

You should make sure your understanding of a function is correct before you use it.

CodePudding user response:

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

2.947893569733893

if I correctly understand what you want.

CodePudding user response:

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
  • Related