0

I've got a bunch of Dates and I want to find their average.

  • How many Dates within 100 years of now can I sum before I run into overflow problems? Any gotchas?
  • What's the best way to calculate the average, avoiding overflow problems?
Riley Lark
  • 20,660
  • 15
  • 80
  • 128
  • 3
    With what type of primitive do you want to sum the dates? Are you storing them as ms from 1/1/1970? – Hidde May 27 '12 at 18:58
  • 1
    This is straightforward algebra: if you're computing the sum with e.g. a 64-bit type, then you can hold values up to 2^63-1. Divide that by the maximum value you're interested in, and that tells you how many you can sum together. – Oliver Charlesworth May 27 '12 at 19:02

1 Answers1

1
System.out.println(Long.MAX_VALUE / System.currentTimeMillis());

Output:

6892653

I think this answers both of your questions. You can also divide each epoch value by 1000*60*60*24, but given the size of that raw quotient, even that's probably overkill.

Marko Topolnik
  • 195,646
  • 29
  • 319
  • 436
  • The denominator should probably be (System.currentTimeMillis() + (100 * 365.25 * 24 * 60 * 60 * 1000)), given that he wants dates within a hundred years. That comes out around 2052416 - fewer than a third as many, but still quite a few. – Tom Anderson May 27 '12 at 19:42
  • @TomAnderson Yes, we're now 42 years into the epoch, and OP needs up to 142 yrs. I had that in mind, but as soon as I saw the magnitude of the quotient, I didn't bother with it. – Marko Topolnik May 27 '12 at 19:46