Java Documentation – Documenting Mathematical Logic in Code

documentationjavamath

Sometimes, although not often, I have to include math logic in my code. The concepts used are mostly very simple, but the resulting code is not – a lot of variables with unclear purpose, and some operations with not so obvious intent. I don't mean that the code is unreadable or unmaintainable, just that it's waaaay harder to understand than the actual math problem. I try to comment the parts which are hardest to understand, but there is the same problem as in just coding them – text does not have the expressive power of math.

I am looking for a more efficient and easy to understand way of explaining the logic behind some of the complex code, preferably in the code itself. I have considered TeX – writing the documentation and generating it separately from the code. But then I'd have to learn TeX, and the documentation will not be in the code itself. Another thing I thought of is taking a picture of the mathematical notations, equations and diagrams written on paper/whiteboard, and including it in javadoc.

Is there a simpler and clearer way?


P.S. Giving descriptive names(timeOfFirstEvent instead of t1) to the variables actually makes the code more verbose and even harder too read.

Best Answer

The right thing to do in such circumstances is to implement the algorithm, formula or whatever with exactly the same variable names as in the primary real-world source (as far as the programming language allows this), and have a succinct comment above it saying something like "Levenshtein distance computation as described in [Knuth1968]", where the citation links to a readily accessible description of the math.

(If you don't have such a reference, but your math is sound and useful, maybe you should consider publishing it yourself. Just sayin'.)