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).
a = log2(64);
--> a=6
import math
a = math.log2(64)
--> a = 6.0
import numpy as np
a = np.log2(64)
--> a = 5.9999999999999991
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With