use*_*039 11 ruby comparison time
time = Time.now
fvalue = time.to_f
return time == Time.at(fvalue)
Run Code Online (Sandbox Code Playgroud)
有人可以在这里解释为什么上面的表达式返回false.如何从float创建一个与原始时间变量匹配的新Time对象?
谢谢
tes*_*ssi 18
IEEE 754 double(返回者to_f)不够精确,无法表示准确的时间.
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
Run Code Online (Sandbox Code Playgroud)
执行以下操作以保留确切时间:
t1 = Time.now
r1 = t1.to_r # value of time as a rational number
t2 = Time.at(r1)
t1 == t2 #=> true
Run Code Online (Sandbox Code Playgroud)
引用自Time.to_r:
该方法旨在用于获得表示自Epoch以来纳秒的精确值.您可以使用此方法将时间转换为另一个Epoch.