英文:
Using floats for counters - Any problems?
问题
我正在查看的代码使用 golang 的 float64 作为计数器,这会在某个时候导致精度丢失的问题吗?具体来说,所有整数都能在 float64 的范围内表示吗?如果不能,我从哪里开始遇到问题?我什么时候会用完连续的整数?
如果你想知道,使用 float64 作为计数器的原因是因为它是一个包含许多不是整数的指标的 []float64 的一部分。
英文:
The code I'm looking at uses a golang float64 as a counter, does this pose a problem with loss of accuracy at some point? Specifically, are all integers represented in the range covered by float64? If not, where do I start running into problems? When do I run out of contiguous integers?
In case you're wondering, the reason for using a float64 as a counter is because it's part of a []float64 that holds many metrics that are not integers.
答案1
得分: 4
根据golang规范,"float64是所有IEEE-754 64位浮点数的集合",通常被称为双精度数。
你可以阅读它的详细信息,如果感兴趣的话,但是为了回答你的问题,引用一下:
"...下一个范围,从2的53次方到2的54次方,每个数都乘以2..."
所以,如果你想将它用作计数器,即正整数,直到2的53次方=9,007,199,254,740,992,你不会遇到问题。
英文:
The golang specification says, "float64 is the set of all IEEE-754 64-bit floating-point numbers." which is commonly known as double precision numbers,
http://en.wikipedia.org/wiki/Double-precision_floating-point_format
You can read all of its glory details if interested, but to answer your question, quote,
"...next range, from 2<sup>53</sup> to 2<sup>54</sup>, everything is multiplied by 2..."
So if you want to use it as counters, i.e. positive integers, you won't have problem until 2<sup>53</sup>=9,007,199,254,740,992.
答案2
得分: 2
是的,float64有52位来存储您的计数器。您应该在2的53次方之前保持准确。
(附注:整个JavaScript语言只使用浮点数。)
英文:
Yes, float64 has 52 bits to store your counter. You should be accurate until 2<sup>53</sup>.
(Side note: the entire JavaScript language uses only Floating Point.)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论