Home > Software engineering >  What happens when you store a numpy array with not enough memory allocated?
What happens when you store a numpy array with not enough memory allocated?

Time:04-20

I was just playing around with np.array and its memory allocation, I expected that if you tried to store an array that was too big for the memory allocation you would just get an error or would just store the first x ammount of digits. Instead I just got back seemingly random numbers. What is going on behind the scenes here?

import numpy as np

def create_new_array(num_list):
  new_array = np.array(num_list,np.int8)
  return print(new_array)

create_new_array([31112 , 32321, 24567,456,324,789])

output: [-120, 65, -9, -56, 68, 21]

Changing the input values slightly gives completly differnt outputs and I'm very curiouse as to why this is.

CodePudding user response:

The numbers are not random; they are the complements. For int8, the maximum positive number it can represent is 127, above which the numbers' complements are returned. For example:

>>> create_new_array([125, 126, 127, 128, 129, 130])
array([ 125,  126,  127, -128, -127, -126], dtype=int8)
  • Related