In the last Numpy getting started tutorial we showed you which software you can use to practice numpy. Also there we showed you how to use one basic numpy function called arange( ) and how to use help function to get help on functions or objects.

Here, we investigate into data types in numpy. Now numpy is a python package which has different functions that are tailored for arrays(matrices). Scientific and engineering application requires different data types for different application. For example, microprocessor and microcontroller are 8 bit devices and for programming requires 8 bit values. In many scientific application, one has to deal with floating point numbers with different precision. To cope with all the different data types required for different scientific and engineering application, Numpy supports different data types.

The following table shows you the different data types in Numpy package.

That means you can work with any of these data types to suit your application. The basic data type is of-course the Boolean, integer, floating point numbers and complex numbers. However, you can see that you have the choice of various integer format, float and complex number. bool_ just means Boolean which is stored as 0 or 1. int_ means builtin integer or default integer which is platform dependent. For example if you are working in 32bit operating system the int_ takes 32 bit and if you are in 64bit computer it will be 64 bit. int8,...int64 are integers with corresponding 8...64 bit support. That means if you have 32 bit integer but want to use 64 bit representation integer then you can tell Numpy that you want to use int64 bit integer. The uint data types are unsigned integers. That means that they are only positive integers. These also comes in 8 to 64 bit flavor. Similarly you can work from 16 to 64 bit floating point numbers. Complex number are supported from 64 bits to 128 bits.

While these are the core data types, they are also the functions to convert to the respective data types. For example if you have a floating point number x = 9.8 and want to convert to integer 32 bit scalar then you can use the int_ as function to do this.

# x = 9.8

# int_(x)
= 9

If you then want to check the data type of the resulting scalar you can use the dtype function.

# int_(x).dtype
= dtype('int32')

Similarly you can convert from floating point to integer.

# float16(5)
= 5.0

# float64(7)
= 7.0

You can also convert integer or floating point numbers to complex numbers.

# complex(4)
= (4+0j)

# complex(9.3)
= (9.3+0j)

But one thing that you cannot do is to convert a complex number to integer or floating point number.

# int32(3-6j)
Traceback (most recent call last):

  File "<ipython-input-25-3b3e1250379d>", line 1, in <module>

TypeError: can't convert complex to int


Post a Comment