【问题标题】:Printing the Float Numbers in Python for Cordinate System在 Python 中为坐标系打印浮点数
【发布时间】:2022-01-05 03:37:21
【问题描述】:

我正在尝试编写一种方法,在给定 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)

非常感谢您的帮助。

【问题讨论】:

    标签: python list for-loop multidimensional-array floating-point


    【解决方案1】:

    首先,您要将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)]
    

    【讨论】:

      【解决方案2】:

      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)
      

      【讨论】:

      • 谢谢兄弟,但它只会将 int 变为浮动。我怎样才能得到 5,56、10,35 等?
      • 你想要的不是浮点数而是字符串,对吗?
      • 不,兄弟,我想要浮动,但您的解决方案只是像这样打印:2.0 5.0 我们怎样才能像这样打印:5.56 2.75?
      • 是的,兄弟,非常感谢。
      猜你喜欢
      • 2019-09-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-12
      • 2020-11-11
      • 1970-01-01
      相关资源
      最近更新 更多