I was wondering how to create numbers in sequence like 1, 2, 3, 4, 5 .... and so on...
OK that was easy to figure out.
But what if I want to create in decimal point like 1.0, 1.1, 1.2, 1.3, 1.4, 1.5 ....
Now that got me thinking.... 🧠
Did quite a lot a tests with the code 💻 and sleepless nights and suddenly it just clicked.... 💡 sitting in the loo 🚽
The script are as follows:-
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | #Number sequence in decimal points using numpy #numpy arange (start, stop, steps) #start from Eg. from the first number start = 1 #stop till Eg. 1 , 1.1, 1.2 ... 2.9 # 3 will not be printed or counted stop = 3 #by how many steps of numbers #1.1,1.2,1.3 or 1.5.2.5.3.5 etc steps = 0.1 import numpy as n x = n.arange(start,stop,steps) for i in x: # round (some number, decimal point) # round (some number only) print(round(i,2)) |
We will use numpy arange.
numpy.arange(start, stop, steps)
start - meaning from where it will start counting. Eg. Number 1
stop - meaning till where it will stop counting. If I say stop till number 10. It will count 1,2,3,4,5,6,7,8,9. It will stop till 10 so the output will be 1 to 9
steps - Assume you are looking at a centimeter scale 📏. To reach 0 to 1 you have to take 0.1, 0.2, 0.3 and so on...
1 2 3 4 5 6 7 | start = 1 stop = 3 steps = 0.1 import numpy as n x = n.arange(start,stop,steps) print (x) |
print(x) will print output as an array
>>> | array[1. 1.1 1.2 1.3 1.4 1.5 1.6 1.7 1.8 1.9 2. 2.1 2.2 2.3 2.4 2.5 2.6 2.7 2.8 2.9] |
Next we use ...
for (gifts) in (santa's bag)
that is...
for i in x: print(i)
This will print out
1.0 1.1 1.2000000000000002 1.3000000000000003 1.4000000000000004 1.5000000000000004 1.6000000000000005 1.7000000000000006 1.8000000000000007 1.9000000000000008 2.000000000000001 2.100000000000001 2.200000000000001 2.300000000000001 2.4000000000000012 2.5000000000000013 2.6000000000000014 2.7000000000000015 2.8000000000000016 2.9000000000000017
To correct this junk we will use "round" function i.e.
print(round(i,2))
In print(round(i, 2)) where "2" is the decimal point.
And this will be our final output
1.0 1.1 1.2 1.3 1.4 1.5 1.6 1.7 1.8 1.9 2.0 2.1 2.2 2.3 2.4 2.5 2.6 2.7 2.8 2.9
Hope you like the tutorial. Try this code 🔴LIVE here
👉 https://code.sololearn.com/cMZVutfULP42
Python is simple and fun to play with and yet very powerful. 🔥