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:
| Type | Min | Max | Power | Bits |
| np.int8 | -128 | 127 | 2**8 | 8 |
| np.int16 | -32768 | 32767 | 2**16 | 16 |
| np.int32 | -2147483648 | 2147483647 | 2**32 | 32 |
| np.int64 | -9223372036854775808 | 9223372036854775807 | 2**64 | 64 |
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).maxWhy 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.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
Challenge
EasyCreate 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
2N-Dimensional Array Creation
Higher DimensionUnderstanding ShapesPopulate with Fixed ValuesNumpy TypesRangeReshape