So it's not flawed (it does compute the correct result).
The author just thinks a completely unreadable (but supposedly faster) variant using logarithms is "better" than the simple loop used in the original snippet?
Write your code for junior devs in their first week at your company, not for academic journals.
His code snippet had rounding errors on the boundaries towards the next unit.
However he notes:
> FWIW, all 22 answers posted, including the ones using Apache Commons and Android libraries, had this bug (or a variation of it) at the time of writing this article.
Sibling commenters have already pointed out that you seem to have misread the post, but tbh I found it quite confusing to follow myslf, so here's a summary:
- the first answer posted on SO was a simple loop
- the author posted a 2nd (supposedly faster but less readable) answer. The author didn't think this answer was better than the loop, but it seems the community did and it became accepted (and extremely popular). THIS is the version that was buggy.
The author later went back and fixed their own buggy version.
So yes there's an argument to be made that the very first simple loop was better, but that's orthogonal to the point of the story.
> Write your code for junior devs in their first week at your company, not for academic journals.
Hard and fast rules about coding style are silly. There's a time and place for clever code, and there's a time and place for verbose and straightforward code.
I write performance-critical code. Juniors shouldn't be mucking about there, because it's performance critical. I also write non-performance-critical code with some effort. I write that stuff for the juniors.
When writing for academic journals, it looks like the stuff I write for juniors. I'll drop a hint here or there so experts can reproduce less-obvious optimizations.
You should almost _always_ focus on code readability and simplicity over inventiveness and cleverness.
Very few people I have encountered have complained about code being 'too simple' or 'too readable', but the opposite happens on a near daily/weekly basis.
Write comments, use a for loop, avoid global state, keep your nesting limited to 2-3 levels, be kind to your junior devs.
The author just thinks a completely unreadable (but supposedly faster) variant using logarithms is "better" than the simple loop used in the original snippet?
Write your code for junior devs in their first week at your company, not for academic journals.