
[英]Rounding errors to 1 significant figure and round values according to number of digits in errors
[英]Why is my decimal rounding to 1 significant figure?
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.