-1

wrote some Python code to plot the coordinates of simple one dimensional linear mapping using matplotlib

Can someone tell me what's wrong with my code?

import matplotlib.pyplot as plt
import numpy as np

result = [10]
result[0] = 1
a = 1.1
x = np.linspace(0, 10, 10)

for i in range(len(result)):
    result[i+1] = a*(result[i] - 1/2) + 1/2
    plt.plot(x, result[i], 'ro')

plt.xlim(0, 10)

plt.ylim(0, 10)

plt.axhline(0, color='b', ls='-', lw=0.5)

plt.axvline(0, color='b', ls='-', lw=0.5)

plt.xlabel(r'$x$', fontsize=18)

plt.ylabel(r'$x_{n+1}$', fontsize=18)

plt.title(r'Graphs of $x_{n+1} = a(x_{n}-\frac{1}{2}) + \frac{1}{2}$', fontsize=20)

plt.show()

error message

 Traceback (most recent call last):
    y[i+1] = a*(y[i] - 1/2) + 1/2
    IndexError: list assignment index out of range
S.Ky
  • 177

1 Answers1

1

suppose the length of result is $n$, then $i$ in the for loop can attain value $n-1$, then you are accessing the $(n-1)+1=n$-th element of result.

However, in Python, the index starts from $0$ and the last index is $n-1$ but you are trying to acess the $n$-th element, hence that is why you have index out of range.

Siong Thye Goh
  • 149,520
  • 20
  • 88
  • 149
  • remark: you might like to post future such question to stackoverflow rather than MSE. – Siong Thye Goh Apr 25 '18 at 08:37
  • Thank you so much. I rewrite "range(len(result)-1)", the error message disappeared. However, any coordinates is entered. Why does that happen? Does that mean that my correction is not there? – S.Ky Apr 25 '18 at 08:43
  • thanks I will try stack overflow from the next – S.Ky Apr 25 '18 at 08:45