time = Time.now
fvalue = time.to_f
return time == Time.at(fvalue)
有人可以解释为什么上面的表达式返回 false 吗?如何从 float 创建一个与原始时间变量匹配的新 Time 对象?
Thanks
IEEE 754 双 https://en.wikipedia.org/wiki/Double_precision#IEEE_754_double-precision_binary_floating-point_format:_binary64(由返回to_f
) 不足以准确地表示exact time.
t1 = Time.now
f1 = t1.to_f
t2 = Time.at(f1)
# they look the same
t1.inspect #=> '2013-09-09 23:46:08 +0200'
t2.inspect #=> '2013-09-09 23:46:08 +0200'
# but double does not have enough precision to be accurate to the nanosecond
t1.nsec #=> 827938306
t2.nsec #=> 827938318
# ^^
# so they are different
t1 == t2 #=> false
执行以下操作以保留准确的时间:
t1 = Time.now
r1 = t1.to_r # value of time as a rational number
t2 = Time.at(r1)
t1 == t2 #=> true
引文来自Time.to_r http://www.ruby-doc.org/core-2.0/Time.html#method-i-to_r:
此方法旨在用于获取准确的值
代表自纪元以来的纳秒。你可以使用这个方法
将时间转换为另一个纪元。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)