Reputation: 113
I want to generate evenly spaced 50 numbers between 0 to 1
First, I tried with numpy.arange(0,1,0.02), below is the output I got.
[0. 0.02 0.04 0.06 0.08 0.1 0.12 0.14 0.16 0.18 0.2 0.22 0.24 0.26
0.28 0.3 0.32 0.34 0.36 0.38 0.4 0.42 0.44 0.46 0.48 0.5 0.52 0.54
0.56 0.58 0.6 0.62 0.64 0.66 0.68 0.7 0.72 0.74 0.76 0.78 0.8 0.82
0.84 0.86 0.88 0.9 0.92 0.94 0.96 0.98]
But later I saw that the endpoint isn't part of this, so I thought of using linspace time = np.linspace(0,1,50) and the output is
[0. 0.02040816 0.04081633 0.06122449 0.08163265 0.10204082
0.12244898 0.14285714 0.16326531 0.18367347 0.20408163 0.2244898
0.24489796 0.26530612 0.28571429 0.30612245 0.32653061 0.34693878
0.36734694 0.3877551 0.40816327 0.42857143 0.44897959 0.46938776
0.48979592 0.51020408 0.53061224 0.55102041 0.57142857 0.59183673
0.6122449 0.63265306 0.65306122 0.67346939 0.69387755 0.71428571
0.73469388 0.75510204 0.7755102 0.79591837 0.81632653 0.83673469
0.85714286 0.87755102 0.89795918 0.91836735 0.93877551 0.95918367
0.97959184 1. ]
I didn't understand why isn't this evenly spaced because 0.02040816+0.02040816=0.04081632 but in the sequence, it shows 0.04081633, someone please explain. To get the output like arrange I have used np.around
Upvotes: 5
Views: 3796
Reputation: 5531
As HansHirse mentioned, it should be np.linspace(0,1,51)
, because np.linspace
does not include the last number.
If you want to achieve the same result using np.arange
, then simply use np.arange(0,1.02,0.02)
. Just add the last number to the 2nd number in np.arange
so that the last number that you expect to be printed would also get printed.
Hope that this helps!
Upvotes: 5
Reputation: 86
To achive evenly spaced 50 numbers between 0 to 1 np.linspace(0,1,50)
is totally right!
If yo want the same result as np.arange(0,1,0.02)
you can use np.linspace(0,0.98,50)
, because the arange function also stopps at 0.98.
numpy.linspace(0,0.98,50)
array([0. , 0.02, 0.04, 0.06, 0.08, 0.1 , 0.12, 0.14, 0.16, 0.18, 0.2 ,
0.22, 0.24, 0.26, 0.28, 0.3 , 0.32, 0.34, 0.36, 0.38, 0.4 , 0.42,
0.44, 0.46, 0.48, 0.5 , 0.52, 0.54, 0.56, 0.58, 0.6 , 0.62, 0.64,
0.66, 0.68, 0.7 , 0.72, 0.74, 0.76, 0.78, 0.8 , 0.82, 0.84, 0.86,
0.88, 0.9 , 0.92, 0.94, 0.96, 0.98])
Upvotes: 0