pythonti-nspire

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

  • 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)