Search code examples
mathcoding-stylefinance

What would be a best practice to program mathematical calculations?


I'm programming some financial software needing to program not very complicated mathematical formulas.

After writing the code, it is not readable anymore - i.e - you can't easily discern what was the original formula.

What would be a good way to program mathematical formulas so they could be easily read later on?

For example, programming a calculation for a loan with a fixed interest rate:

(TotalValue*monthlyInterest*Math.pow((1+monthlyInterest),totalPayments))/(Math.pow((1+monthlyInterest),totalPayments) - 1)

Though using meaningful variables, the formula is not readable. But if you will look at this formula written in a classical mathematical notation on a page - you will easily know what's going on (really basic math).

How would you even take this formula and write it in a readable way.

Clarification

I'm not talking about any specific language. This should be the same for any high-level language. The example uses Javascript.


Solution

  • You could also add local variables that are abbreviations of the long name. As they are local, their definition will be right above the formula. This could look like

    TV = TotalValue;
    mi = monthlyInterest;
    N = totalPayments;
    
    MR = ( TV*mi*Math.pow( 1+mi, N ) ) / ( Math.pow( 1+mi, N ) - 1)
    
    MonthlyRate = MR;
    

    where you then see that you can simplify the formula to

    MR = (TV*mi) / ( 1 - Math.pow( 1+mi , -N) - 1)