Closest Harmonic Number to an Integer

(johndcook.com)

24 points | by ibobev 6 days ago

3 comments

  • mackeye 47 minutes ago
    > For small n we can directly implement the definition. For large n, the direct approach would be slow and would accumulate floating point error.

    is there a reason the direct definition would be slow, if we cache the prior harmonic number to calculate the next?

    • coherentpony 19 minutes ago
      It’s a natural observation, but it doesn’t address the floating point problem. I think the author should have said “fast or would accumulate floating point error” instead of “fast and would accumulate floating point error”.

      You could compute in the reverse direction, starting from 1/n instead of starting from 1, this would produce a stable floating point sum but this method is slow.

      Edit: Of course, for very large n, 1/n becomes unrepresentable in floating point.

  • jcla1 1 hour ago
    Interesting follow-up question: What is the distance between the set of harmonic numbers and the integers? i.e. is there a lower bound on the difference between a given integer and its closest harmonic number? If so, for which integer is this achieved?
    • Someone 2 minutes ago
      [delayed]
    • jcla1 1 hour ago
      Spoiler: there is a simple argument against the existence of such a lower bound.