I am trying to write a method that generates and returns n random points in a 2-dimensional space given the width and height in Python I coded an algorithm but I want to recieve float points in the system. Here my code is:
import random
npoints = int(input("Type the npoints:"))
width = int(input("Enter the Width you want:"))
height = int (input("Enter the Height you want:"))
allpoints = [(a,b) for a in range(width) for b in range(height)]
sample = random.sample(allpoints, npoints)
print(sample)
Output is:
Type the npoints:4
Enter the Width you want:10
Enter the Height you want:8
[(8, 7), (3, 3), (7, 7), (9, 0)]
How can I print them as float. For example: (8.75 , 6.31)
Thanks a lot for the help.
CodePudding user response:
First you want to take float
as input. For height
& width
replace the int()
with float()
.
Now, you can't generate all point within the box defined by these any more since floating points can have arbitrary precision (theoretically).
So you need a way to generate the coordinates separately. A random y-coordinate between 0 & height
can be generated by:
<random number between 0 to 1> * height
Similarly for the width. And you can use random.random()
to get the random number between 0 to 1.
Full code:
import random
npoints = int(input("Type the npoints:"))
width = float(input("Enter the Width you want:"))
height = float(input("Enter the Height you want:"))
sample = []
for _ in range(npoints):
sample.append((width * random.random(), height * random.random()))
print(sample)
Output:
Type the npoints:3
Enter the Width you want:2.5
Enter the Height you want:3.5
[(0.7136697226350142, 1.3640823010874898), (2.4598008083240517, 1.691902371689177), (1.955991673900633, 2.730363157986461)]
CodePudding user response:
Change a
and b
to float
:
import random
npoints = int(input("Type the npoints:"))
width = int(input("Enter the Width you want:"))
height = int (input("Enter the Height you want:"))
# HERE ---------v--------v
allpoints = [(float(a),float(b)) for a in range(width) for b in range(height)]
sample = random.sample(allpoints, npoints)
print(sample)
Output:
Type the npoints:4
Enter the Width you want:10
Enter the Height you want:8
[(1.0, 0.0), (8.0, 7.0), (5.0, 1.0), (2.0, 5.0)]
Update
I want float but your solve is printing only like this: 2.0 5.0
How can we print like this: 5.56 2.75 ?
Print with 2 decimals:
>>> print(*[f"({w:.2f}, {h:.2f})" for w, h in sample])
(1.00, 0.00) (8.00, 7.00) (5.00, 1.00) (2.00, 5.00)