rougier/numpy-100

There is a wrong answer in 66

artfintl opened this issue · 1 comments

  1. Considering a (w,h,3) image of (dtype=ubyte), compute the number of unique colors (★★★)

Author: Nadav Horesh

w,h = 16,16
I = np.random.randint(0,2,(h,w,3)).astype(np.ubyte)
F = I[...,0] * 256 * 256 + I[...,1] * 256 +I[...,2]
n = len(np.unique(F))
print(np.unique(I))

In numpy 1.19.0. F = I[...,0] * 256 * 256 + I[...,1] * 256 +I[...,2] Cause of 256 is a uint16, the data type of F covert to uint16 but I[...,0]*256*256 expected to be a uint32 other wise will cause I[...,0]* 256 * 256 overflow to a zero matrix. So n will be a wrong answer 4.

Should correct to F = I[...,0]*65536 + I[...,1]*256 +I[...,2]

Thanks. That is quite a subtle error indeed:

>>> (np.ones(1, dtype=np.ubyte) * 256 * 256).dtype
dtype('uint16')
>>> (np.ones(1, dtype=np.ubyte) * (256 * 256)).dtype
dtype('uint32')

Can you make a PR?

P.S.: I edited your comment to add backquotes around your code to have a nicer display.