How can I make a sequence of numbers -0.05 to 0.05 with 0.002 increment and store it in a vector?
Code
import numpy as np
x=np.zeros(50)
for i in range(-0.05,0.05,0.002):
x(i)
CodePudding user response:
You can use Numpy's arange()
:
import numpy as np
np.arange(-0.05,0.05,0.002)
Which creates:
array([-5.00000000e-02, -4.80000000e-02, -4.60000000e-02, -4.40000000e-02,
-4.20000000e-02, -4.00000000e-02, -3.80000000e-02, -3.60000000e-02,
-3.40000000e-02, -3.20000000e-02, -3.00000000e-02, -2.80000000e-02,
-2.60000000e-02, -2.40000000e-02, -2.20000000e-02, -2.00000000e-02,
-1.80000000e-02, -1.60000000e-02, -1.40000000e-02, -1.20000000e-02,
-1.00000000e-02, -8.00000000e-03, -6.00000000e-03, -4.00000000e-03,
-2.00000000e-03, 4.16333634e-17, 2.00000000e-03, 4.00000000e-03,
6.00000000e-03, 8.00000000e-03, 1.00000000e-02, 1.20000000e-02,
1.40000000e-02, 1.60000000e-02, 1.80000000e-02, 2.00000000e-02,
2.20000000e-02, 2.40000000e-02, 2.60000000e-02, 2.80000000e-02,
3.00000000e-02, 3.20000000e-02, 3.40000000e-02, 3.60000000e-02,
3.80000000e-02, 4.00000000e-02, 4.20000000e-02, 4.40000000e-02,
4.60000000e-02, 4.80000000e-02])
You can pass this to around
to round to a precision desired:
np.around(np.arange(-0.05,0.05,0.002), 3)
Which makes:
array([-0.05 , -0.048, -0.046, -0.044, -0.042, -0.04 , -0.038, -0.036,
-0.034, -0.032, -0.03 , -0.028, -0.026, -0.024, -0.022, -0.02 ,
-0.018, -0.016, -0.014, -0.012, -0.01 , -0.008, -0.006, -0.004,
-0.002, 0. , 0.002, 0.004, 0.006, 0.008, 0.01 , 0.012,
0.014, 0.016, 0.018, 0.02 , 0.022, 0.024, 0.026, 0.028,
0.03 , 0.032, 0.034, 0.036, 0.038, 0.04 , 0.042, 0.044,
0.046, 0.048])
CodePudding user response:
You can use np.arange()
like this:
np.arange(-0.05, 0.05, 0.002)
but it has precision problems around 0, as seen here:
array([-5.00000000e-02, -4.50000000e-02, -4.00000000e-02, -3.50000000e-02,
-3.00000000e-02, -2.50000000e-02, -2.00000000e-02, -1.50000000e-02,
-1.00000000e-02, -5.00000000e-03, -2.77555756e-17, 5.00000000e-03,
^^^^^^^^^^^^^^^
Another approach is to use integers and then divide after, like this:
np.arange(-50, 50, 2) / 1000
which produces:
array([-0.05 , -0.048, -0.046, -0.044, -0.042, -0.04 , -0.038, -0.036,
-0.034, -0.032, -0.03 , -0.028, -0.026, -0.024, -0.022, -0.02 ,
-0.018, -0.016, -0.014, -0.012, -0.01 , -0.008, -0.006, -0.004,
-0.002, 0. , 0.002, 0.004, 0.006, 0.008, 0.01 , 0.012,
0.014, 0.016, 0.018, 0.02 , 0.022, 0.024, 0.026, 0.028,
0.03 , 0.032, 0.034, 0.036, 0.038, 0.04 , 0.042, 0.044,
0.046, 0.048])
CodePudding user response:
It is in fact very simple with NumPy.
Just use np.arange()
import numpy as np
step = 0.002
mini = -0.05
maxi = 0.05
for i in np.arange(mini, maxi step, step):
print(round(i, 3))
***note This also rounds it to 3 decimal places as other wise it prints with about 46 decimal places.