我用来执行代码的秒表无缘无故四舍五入到一位有效数字。
FormTime
是从 FORM
手动定义的
我已将其从 FORM=[[1, 1, 0, 0, 0],
缩减为只包括用于调试目的的时间
FORM=[[1], [1.875], [2.25], [4.562], [5.438]]
stopwatch
定义如下;
import datetime
from math import floor
a = datetime.datetime.now()
while True:
b = datetime.datetime.now()
c = (b - a)
roundMicro = floor(c.microseconds/1e3)
stopwatch = float(str(c.seconds)+'.'+str(roundMicro))
...
stopwatch
在循环输出中运行;
>>> stopwatch
0.0
...
0.123
...
0.2
例如这里是它打算执行的时间 (FormTime
) 与它实际执行的时间 (Ex
这只是 stopwatch
)
count = 0
a = datetime.datetime.now()
while True:
b = datetime.datetime.now()
c = (b - a)
roundMicro = floor(c.microseconds/1e3)
stopwatch = float(str(c.seconds)+'.'+str(roundMicro))
if FORM[count][0]<=stopwatch:
print(f'FormTime = {FORM[count][0]}', end="")
print(f'{" "*int(7-len(str(FORM[count][0])))}', end="") #Just decorative spacing in terminal
print(f'Ex ≈ {stopwatch}') #Ex = Executed @
count+=1
返回;
FormTime = 1 Ex ≈ 1.0
FormTime = 1.875 Ex ≈ 1.9
FormTime = 2.25 Ex ≈ 2.3
FormTime = 4.562 Ex ≈ 4.6
FormTime = 5.438 Ex ≈ 5.5
知道为什么它在 stopwatch
= 一位有效数字时执行吗?
或者为什么它是四舍五入的?
- 不要介意
Exception has occurred: IndexError list index out of range, line 21
这将在演示结束时发生
最佳答案
roundMicro = floor(c.microseconds/1e3)
stopwatch = float(str(c.seconds)+'.'+str(roundMicro))
这两行可能不是您所期望的。假设 c.microseconds == 3000
,您将得到 roundMicro = 3
并以 1.3
结尾,而它应该是 1.003
.
除非您正在学习数学舍入,否则在这里没有必要重新发明轮子。使用格式字符串来获得所需的精度(以及可选的布局):
stopwatch = "{:.3f}".format(c.seconds + c.microseconds * 1e-6)
# => 1.003
如果您需要将截断后的值作为数字,您仍然可以调用 float(stopwatch)
来转换字符串。
关于python - 为什么我的小数点四舍五入到一位有效数字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66097983/