[Numpy-discussion] can int and float exists in one array?(about difference in indexing Matlab matrix and Numpy array)
Robert
kxroberto at googlemail.com
Mon Nov 27 13:13:18 CST 2006
Zhang Sam wrote:
> Hi, there
>
> I have a practical problem. For some reason, I hope int and float can
> exist one array as shown in matlab code.
You can use 'object' as array type:
>>> a=numpy.array([1,2.0,2])
>>> b=numpy.array([1,2.0,2],object)
>>> a
array([ 1., 2., 2.])
>>> b
array([1, 2.0, 2], dtype=object)
>>>
strangely this often leads to even faster code compared to using float/int arrays. Especially when you do much computations in Python - because with numpy you cannot really create int/float arrays, but only numpy.int32/numpy.float64 arrays. Even if you write "numpy.array([1,2.0,2],float)", you'll get item instances of another type out, which compute a lot slower and cause other problems. So currently the only way to put int's & float's into an array anyway requires to use type 'object'.
>>> import timeit
>>> timeit.Timer('a[0]+a[1]',glbls=globals()).timeit(10000)
0.069539285020861596
>>> timeit.Timer('a[0]+a[1]',glbls=globals()).timeit(10000)
0.037078734867140639
>>> timeit.Timer('a[0]+a[1]',glbls=globals()).timeit(10000)
0.038550709657232396
>>> timeit.Timer('b[0]+b[1]',glbls=globals()).timeit(10000)
0.013452827105121301
>>> timeit.Timer('b[0]+b[1]',glbls=globals()).timeit(10000)
0.01344221123075684
>>> b.sum()
5.0
>>> timeit.Timer('a.sum()',glbls=globals()).timeit(10000)
0.18172588974296389
>>> timeit.Timer('b.sum()',glbls=globals()).timeit(10000)
0.15798208990248241
>>>
Robert
More information about the Numpy-discussion
mailing list