I am working on generating a simple sine function defined over the range [0,1] as shown below. However I got an index error when assigning function[i]
. I tried to set x_n = int(x_n)
as some questions with the same error suggest but that only creates further errors.
import numpy as np
function = np.zeros(20)
x_n=np.arange(0,1,0.05) #[0,1]
for i in x_n:
function[i] = np.sin(2*np.pi*i)
Note x_n
has a step of 0.05 because I need to generate 20 values ranging from 0 to 1.
CodePudding user response:
You don't need to create array zero and insert numbers in this, you can do this with vectorizing magic in NumPy
like below:
x_n=np.arange(0,1,0.05) #[0,1]
np.sin(x_n*np.pi*2)
Output:
array([ 0.00000000e 00, 3.09016994e-01, 5.87785252e-01, 8.09016994e-01,
9.51056516e-01, 1.00000000e 00, 9.51056516e-01, 8.09016994e-01,
5.87785252e-01, 3.09016994e-01, 1.22464680e-16, -3.09016994e-01,
-5.87785252e-01, -8.09016994e-01, -9.51056516e-01, -1.00000000e 00,
-9.51056516e-01, -8.09016994e-01, -5.87785252e-01, -3.09016994e-01])
CodePudding user response:
The problem is that i is a float, while array indices are ints. You should change your code to
import numpy as np
function = np.zeros(20)
x_n=np.arange(0,1,0.05) #[0,1]
for i in x_n:
function[int(i*20)] = np.sin(2*np.pi*i)
CodePudding user response:
A basic Python iteration tool is enumerate
. With this you can iterate on an array of floats, and still get a sequential integer index.
In [16]: arr = np.zeros(20)
...: x_n=np.arange(0,1,0.05) #[0,1]
...:
...: for i,v in enumerate(x_n):
...: arr[i] = np.sin(2*np.pi*v)
...:
In [17]: arr
Out[17]:
array([ 0.00000000e 00, 3.09016994e-01, 5.87785252e-01, 8.09016994e-01,
9.51056516e-01, 1.00000000e 00, 9.51056516e-01, 8.09016994e-01,
5.87785252e-01, 3.09016994e-01, 1.22464680e-16, -3.09016994e-01,
-5.87785252e-01, -8.09016994e-01, -9.51056516e-01, -1.00000000e 00,
-9.51056516e-01, -8.09016994e-01, -5.87785252e-01, -3.09016994e-01])
An alternative is to iterate with for i in range(len(x_n)):
, but enumerate
is clearer.
But you don't need to iterate (in python) at all:
In [18]: np.sin(2*np.pi*x_n)
Out[18]:
array([ 0.00000000e 00, 3.09016994e-01, 5.87785252e-01, 8.09016994e-01,
9.51056516e-01, 1.00000000e 00, 9.51056516e-01, 8.09016994e-01,
5.87785252e-01, 3.09016994e-01, 1.22464680e-16, -3.09016994e-01,
-5.87785252e-01, -8.09016994e-01, -9.51056516e-01, -1.00000000e 00,
-9.51056516e-01, -8.09016994e-01, -5.87785252e-01, -3.09016994e-01])