Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python NumPy log2 vs MATLAB

I'm a Python newbie coming from using MATLAB extensively. I was converting some code that uses log2 in MATLAB and I used the NumPy log2 function and got a different result than I was expecting for such a small number. I was surprised since the precision of the numbers should be the same (i.e. MATLAB double vs NumPy float64).

MATLAB Code

a = log2(64);

--> a=6

Base Python Code

import math

a = math.log2(64)

--> a = 6.0

NumPy Code

import numpy as np

a = np.log2(64)

--> a = 5.9999999999999991

Modified NumPy Code

import numpy as np

a = np.log(64) / np.log(2)

--> a = 6.0

So the native NumPy log2 function gives a result that causes the code to fail a test since it is checking that a number is a power of 2. The expected result is exactly 6, which both the native Python log2 function and the modified NumPy code give using the properties of the logarithm. Am I doing something wrong with the NumPy log2 function? I changed the code to use the native Python log2 for now, but I just wanted to know the answer.

like image 739
Hesse34 Avatar asked Jul 17 '13 14:07

Hesse34


1 Answers

No. There is nothing wrong with the code, it is just because floating points cannot be represented perfectly on our computers. Always use an epsilon value to allow a range of error while checking float values. Read The Floating Point Guide and this post to know more.

EDIT - As cgohlke has pointed out in the comments,

Depending on the compiler used to build numpy np.log2(x) is either computed by the C library or as 1.442695040888963407359924681001892137*np.log(x) See this link.

This may be a reason for the erroneous output.

like image 132
Sukrit Kalra Avatar answered Oct 11 '22 09:10

Sukrit Kalra