在 Python 中打印浮点数用于 cordinate 系统



我正在尝试编写一种方法,该方法在给定 Python 中的宽度和高度的情况下,在二维空间中生成并返回 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作为输入。对于heightwidth,请将int()替换为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)]

更新

我想要浮点数,但您的解决方案是仅像这样打印:2.0 5.0
我们如何这样打印:5.56 2.75 ?

打印时有2 位小数:

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

最新更新