2

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.

JnBrymn
  • 24,245
  • 28
  • 105
  • 147
  • 4
    Using a slice for data that is not homogenous is a bad idea and generally a code smell. Use a struct instead and embed a slice if neccessary. – fuz Feb 17 '14 at 23:08
  • float64 cannot represent all int64, but the unrepresentable numbers are impressively big :-) – Volker Feb 17 '14 at 23:19

2 Answers2

4

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 253 to 254, everything is multiplied by 2..."

So if you want to use it as counters, i.e. positive integers, you won't have problem until 253=9,007,199,254,740,992.

Eric Postpischil
  • 195,579
  • 13
  • 168
  • 312
Bin He
  • 136
  • 1
  • 2
  • Hm... ok. Is it safe to assume that no disk will ever make 9quadrillion reads? That's what the counter is for. – JnBrymn Feb 18 '14 at 15:57
2

Yes, float64 has 52 bits to store your counter. You should be accurate until 253.

(Side note: the entire JavaScript language uses only Floating Point.)

Eric Postpischil
  • 195,579
  • 13
  • 168
  • 312
BraveNewCurrency
  • 12,654
  • 2
  • 42
  • 50