You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python二维坐标系下随机浮点数坐标点的生成与输出方法

解决方案

你当前的代码使用range()生成整数序列构造所有候选坐标,所以输出都是整数类型,且该方案在宽高数值较大时会生成大量冗余数据,占用额外内存。
可以使用random.uniform(a,b)方法直接生成[a,b)区间内的随机浮点数,直接循环生成指定数量的坐标即可,无需预先构造全量候选池。

修改后的完整代码如下:

import random    

npoints = int(input("Type the npoints:"))
width = int(input("Enter the Width you want:"))
height = int (input("Enter the Height you want:"))

# 直接生成n个浮点坐标,x取值范围0~width,y取值范围0~height
sample = [(random.uniform(0, width), random.uniform(0, height)) for _ in range(npoints)]

# 如果需要固定保留N位小数,可以用round方法处理,示例为保留2位小数
# sample = [(round(random.uniform(0, width), 2), round(random.uniform(0, height), 2)) for _ in range(npoints)]

print(sample)

运行效果示例:
输入参数和你测试时一致的情况下,输出类似:

Type the npoints:4
Enter the Width you want:10
Enter the Height you want:8
[(8.75, 6.31), (2.14, 7.92), (5.66, 1.08), (9.47, 0.32)]

补充说明:

  • 如果需要调整坐标的取值区间,只需要修改random.uniform()的两个入参即可,比如要生成x坐标在3~10之间的点,就改成random.uniform(3, width)
  • 如果对浮点数精度有要求,除了round()之外也可以使用decimal模块做更高精度的处理

内容的提问来源于stack exchange,提问作者user16726326

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 18:36:04