'How to put mathematical equations in source code without making it unreadable?

When implementing complex calculations, I found that readability suffered a lot. For example, this formula is absolutely unreadable when translated to code (I chose Rust since the strong typing makes it even worse):

let s2 = (2.0 * (s as f64) * ((180.0 - a) / 2.0).sin()) / a.sin();

How do you deal with math in your code? I thought of putting the math in a LaTeX file and converting it to actual code during compilation, is that something which has been done before?



Solution 1:[1]

After digging through the internet I came across a Pull Request at the rust-num crate.

You can use the RUSTDOCFLAGS environment variable to embed html pages which can contain javascript. In this case kaTeX is used. (the following is a summary of the PR).

  1. Add --html-in-header doc/header.html --html-after-content doc/after.html to the RUSTDOCFLAGS environment variable
  2. Put your formula into your doc comment, e.g. $s' = \frac{2 \cdot s \cdot \sin \left( \frac{180 - \alpha}{2} \right) }{\sin \left( \alpha \right) } $
  3. Content of doc/after.html:
    <script>renderMathInElement(document.body, {
      delimiters: [
        {left: "$$", right: "$$", display: true},
        {left: "\\[", right: "\\]", display: true},
        {left: "\\(", right: "\\)", display: false},
        {left: "$", right: "$", display: false}
      ]
    });</script>
    
  4. Content of doc/header.html
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/KaTeX/0.6.0/katex.min.css">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/KaTeX/0.6.0/katex.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/KaTeX/0.6.0/contrib/auto-render.min.js"></script>
    

Of course you can alter the links to use a local katex resource instead of a cdn.

Solution 2:[2]

My solution to this problem, which is not limited to Rust specifically, is to store all calculations (except calculations that are iterative, GPU-specific or otherwise specialized) in Microsoft Excel and to then (re)generate code from Excel whenever I need it.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Dmitri Nesteruk