打印坐标系 Python 中的浮点数

Printing the Float Numbers in Python for Cordinate System

我正在尝试编写一种方法,在给定 Python 中的宽度和高度的情况下,在二维 space 中生成 returns n 个随机点 我编写了一个算法,但我想要在系统中获得浮点数。 我的代码是:

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)]

如何将它们打印为浮点数。例如:(8.75 , 6.31)

非常感谢您的帮助。

首先您想将 float 作为输入。对于 height & widthint() 替换为 float()

现在,您不能再在由这些定义的框中生成所有点,因为浮点可以具有任意精度(理论上)。

所以你需要一种单独生成坐标的方法。 0 和 height 之间的随机 y 坐标可以通过以下方式生成:

<random number between 0 to 1> * height

宽度也一样。您可以使用 random.random() 来获取 0 到 1 之间的随机数。

完整代码:

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)

输出:

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)]

ab改为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)

输出:

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)]

更新

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(*[f"({w:.2f}, {h:.2f})" for w, h in sample], sep=', ')
(1.00, 0.00), (8.00, 7.00), (5.00, 1.00), (2.00, 5.00)