'MemoryError: memory allocation failed, allocating x bytes

So, I'm coding a program that allows me to graph Collatz sequences with a given starting value in my Ti-nspire CX II-T, it had been running fine (no errors concerning memory) until now. Every time I run the program I get a weird output regarding memory allocation.

Code:

from math import *
import ti_plotlib as plt
start_x = int(input("x? "))
cur_x = 0
n = 1
x = [start_x]
y = [1]
xmax = cur_x
while cur_x!=1:
  if fmod(cur_x,2) == 0:
    cur_x=cur_x/2
  else:
    cur_x=3*cur_x+1
  x+=[cur_x]
  n=n+1
  y+=[n]
  if cur_x>xmax: 
    xmax = x.max()
plt.grid(1,1,"dotted")
plt.axes("on")
plt.window(0,plt.xmax,0,y.max()+1)
plt.plot(x,y)

Output received:

 Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
  File "C:\Users\-------\AppData\Roaming\Texas Instruments\TI-Nspire CX Student Software\python\doc9\prob3xplus1.py", line 14, in <module>
MemoryError: memory allocation failed, allocating 95112 bytes

So far I've tried:

  1. Reducing the libraries included;
  2. Removing notations and extra stuff;

Both of these helped lower the number of allocated bytes.

  1. Included micropython and checked memory data:
mem: total=19112938, current=18770377, peak =18770617 stack: 7432 out of 131070 
GC: total: 2072832, used: 26688, free: 2046144 
No. of 1-blocks: 295, 2-blocks: 40, max blk sz: 41, max free sz: 63922

Any help regarding this issue would be appreciated.



Solution 1:[1]

Your program got caught in an infinite loop:

Your loop ends when cur_x becomes 1, but you forgot to initialize it to start_x, and so it is initially 0. In the loop, since it is 0, it is a multiple of 2, and so you keep dividing it.

Unrelated to the memory error, you also messed up the x and y lists at some point...

This should work:

from math import *
import ti_plotlib as plt
start_x = int(input("x? "))
cur_x = 0
n = 1
y = [start_x]
x = [1]
cur_x = start_x
xmax = cur_x
iter = 0
while cur_x!=1:
  if iter>10:
    break
  iter = iter+1
  if cur_x%2 == 0:
    cur_x=cur_x/2
  else:
    cur_x=3*cur_x+1
  y+=[cur_x]
  n=n+1
  x+=[n]
  if cur_x>xmax: 
    xmax = cur_x
plt.grid(1,1,"dotted")
plt.axes("on")
plt.window(0,n+1,0,xmax)
plt.plot(x,y)

Solution 2:[2]

Apparently my code got stuck in an infinite loop. This code ended up working:

start_x = 1
while start_x<=1:
  start_x = int(input("x? "))
cur_x = start_x
val = []
y = []
val.append(cur_x)
n = 0
y.append(0)
xmax = cur_x
while cur_x>1:
  if fmod(cur_x,2) == 0:
    cur_x=round(cur_x/2)
  else:
    cur_x=round(3*cur_x+1)
  n=n+1
  val.append(cur_x)
  y.append(n)
  if cur_x>xmax: 
    xmax = cur_x
plt.auto_window(y,val)
plt.color(200,0,0)
plt.axes("axes")
plt.text_at(1,"n","left")
plt.title("Collatz conjecture")
plt.plot(y,val,"o")
print(val)
print(y)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Promitheas Nikou
Solution 2 Bernas