首页 > 解决方案 > 为什么内联浮点打印与python出错

问题描述

打印时出现奇怪的舍入效果。使用下面的 python 代码,我试图把它全部放在一行上。但是,变量s似乎错误地打印在第一行

s = gb.score(train, y)
if (s>0.96)&(s<1.0):
   print("LR: {0:.3f} estimators: {0:.3f} score: {0:.16f}".format(learning_rate,est,s))
   print (s)

我从中得到的输出是:

LR:0.003 估计:0.003 得分:0.0025000000000000
0.9696969696969697

为什么 S 在第一行四舍五入为 0.00250000 ?我希望它显示为第二行。

标签: pythonfloating-point

解决方案


因为0in{0:.16f}会插入第一个参数。这就是为什么在所有三个地方只有你的值learning_rate被插入和格式化。

尝试

print("LR: {0:.3f} estimators: {1:.3f} score: {2:.16f}".format(learning_rate,est,s))

或仅使用参数的顺序:

print("LR: {:.3f} estimators: {:.3f} score: {:.16f}".format(learning_rate,est,s))

为避免混淆,您还可以使用名称进行插入:

print("LR: {learningrate:.3f} estimators: {estimators:.3f} score: {score:.16f}".format(learningrate=learning_rate,estimators=est,score=s))

推荐阅读