繁体   English   中英

为什么我的十进制四舍五入到 1 位有效数字?

[英]Why is my decimal rounding to 1 significant figure?

我在 python 中用于执行代码的秒表无缘无故地四舍五入到一个有效数字。


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 as 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)来转换字符串。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM