从float转换的Ruby Time对象不等于orignial Time对象

[英]Ruby Time object converted from float doesn't equal to orignial Time object


time = Time.now
fvalue = time.to_f
return time == Time.at(fvalue)

Can somebody here explain why the above expression returns false. How can I create a new Time object from float that matches the original time variable?

有人可以在这里解释为什么上面的表达式返回false。如何从float创建一个与原始时间变量匹配的新Time对象?

Thanks

谢谢

1 个解决方案

#1


17  

IEEE 754 double (which is returned by to_f) is not accurate enough to represent the exact time.

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

Do the following, to preserve the exact time:

执行以下操作以保留确切时间:

t1 = Time.now
r1 = t1.to_r # value of time as a rational number
t2 = Time.at(r1)
t1 == t2 #=> true

Citation from Time.to_r:

引自Time.to_r:

This methods is intended to be used to get an accurate value representing the nanoseconds since the Epoch. You can use this method to convert time to another Epoch.

该方法旨在用于获得表示自Epoch以来纳秒的精确值。您可以使用此方法将时间转换为另一个Epoch。


注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:http://www.itdaan.com/blog/2013/09/09/e20e05bd4afe92c1f26f72dc54dbf321.html



 
© 2014-2018 ITdaan.com 粤ICP备14056181号