Python生成指定区间随机浮点数写入Excel的报错解决与功能实现咨询
问题原因与解决方案
1. 报错修复
报错的核心原因是input()函数默认返回字符串类型,而random.uniform()要求传入数值型参数,因此需要先把输入的起止值转为浮点数即可解决类型错误。
2. 需求实现说明
由于random.uniform(start, end)生成的是闭区间[start, end]内的随机数,直接随机生成很难刚好触发等于end的停止条件,因此默认调整为生成递增的随机浮点数(和你原代码排序后的输出逻辑一致),当生成值和end的差值小于0.01(可自行调整精度阈值)时停止生成,最后写入end值匹配原表格结构。
修正后的完整代码:
import xlsxwriter import random wb = xlsxwriter.Workbook('abc.xlsx') ws = wb.add_worksheet() # 输入转浮点数,修复类型报错 start = float(input("Enter the start value:")) end = float(input("Enter the end value:")) ws.write('A1','InputRPM') ws.write('A3', start) row = 3 col = 0 last_val = start # 停止判断的精度阈值,可根据需要自行调整 threshold = 0.01 while True: # 生成大于上一个值、小于等于end的随机浮点数 current_val = random.uniform(last_val, end) # 达到阈值就停止生成 if end - current_val < threshold: break ws.write(row, col, current_val) row += 1 last_val = current_val # 最后写入区间结束值 ws.write(row, col, end) wb.close()
如果不需要生成的数值是递增的,想要完全随机的区间值,直到出现接近end的数值就停止,可以把上面的while循环替换为以下逻辑:
while True: current_val = random.uniform(start, end) ws.write(row, col, current_val) row += 1 if end - current_val < threshold: break
内容的提问来源于stack exchange,提问作者Someshwaran
相关产品推荐
相关产品推荐

