Menu
Coddy logo textTech

Numpy Types

Lesson 7 of 18 in Coddy's Numpy Fundamentals course.

The program must allocate sufficient space to allow the fixed-size array to store its data internally. How can a computer determine the amount of space to allocate?

This is where the dtype comes in. Each dtype has a maximum and a minimum value that allows the machine to know how much space to allocate for each cell in the array.  There are many Numpy types.

Int types are n-bit integers:

TypeMinMaxPowerBits
np.int8-1281272**88
np.int16-32768327672**1616
np.int32-214748364821474836472**3232
np.int64-922337203685477580892233720368547758072**6464

Float types:

Type
np.float16
np.float32
np.float64
np.float128

I can't show the minimum and the maximum values because they are too big.

To see for yourself what is the maximum value and the minimum value you can use the numpy.iinfo(<i>type</i>) for integer types and numpy.finfo(<i>dtype</i>) for float types:

np.iinfo(np.int16).min
np.iinfo(np.int16).max

Why should we care of dtypes?

Assume that we have an array that each element represents a room of people. The program keeps track of the number of people in each room.

Let's assign the array to be np.int8:

rooms = np.array([125, 3, 127], dtype=np.int8)

Here we have 3 rooms. Each room has a number that is a np.int8 type. 

The last room has 127 people! 

This is the maximum value of np.int8

What will happen if another person comes into that room?

rooms[-1] += 1
print(rooms)

Output:

[ 125    3 -128]

Look at that! From 127 the number turned to -128. This is not the anticipated number, this is why we need to make sure we are using the right dtype for our needs.

quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

challenge icon

Challenge

Easy

Create a function named dtype_converter that receives the number of bits for the type and a value.

The functions return a 0-dimension numpy array (Remember that a 0-dimension array is just a single value passed into the np.array) with the specified dtype and the value incremented by one

bits can be one of the following values: 8, 16, 32, 64

Watch closely at the output, some test cases will overflow!

Try it yourself

import numpy as np

def dtype_converter(bits, value):
    try:
        if bits == 8:
            return np.array(value+1, dtype=np.int8)
        # Write your code here
    except:
        print("Overflow:", value+1)

All lessons in Numpy Fundamentals