Rendering mathematical equations
Rendering mathematical equations
For a while I've been wanting to expand the capabilities of my blogging setup to allow for the rendering of mathematical equations. There were a few requirements for doing so:
- Equations must fit in a markdown syntax
- Equations must be rendered as a set of vectors, not as an image in bitmap format
- Equations must be visible in the sourcecode on GitHub as well
GitHub support
Since the 19th of May 2022 [1] GitHub supports the rendering of equations in TeX format. TeX [2] is a mathematical typesetting system released in 1978 by computer scientist Donald Knuth. It allows for free, accessible and reproducible results. It is still wildly used in academics to this day. Below is an example of how TeX notation get's converted:
Image: From TeX notation to rendered output
GitHub makes use of MathJax to render these equations under the hood. There are two ways [3] to indicate a piece of text is a mathematical equation:
- Using a dollar or double dollar sign delimiter: $
- Using a code block with triple backticks where the language is set to 'math'
Since my current blogging setup already uses triple backticks to display code, it seems to be the most straight forward solution. This means that we can write our equation as code with the language set to 'math', while still being valid Markdown syntax:
Image: TeX syntax as valid markdown by making use of a code block
Mathlifier
At this point we have satisfied 2 out of the 3 requirements: Markdown syntax and rendering on GitHub. The most important one remains: rendering our equations into HTML. For this I've opted for the NPM package Mathlifier. It is a wrapper around KaTeX, which in its turn is a package for rendering TeX equations on the web!
Because all code blocks are rendered by a separate Svelte component, I can now add some logic to detect when the code language is set to 'math' like so:
Inside of the Math.svelte component I can make use of Mathlifier to correctly display the equation like so:
And that's how I render TeX syntax to HTML on this blog!
An example with the quadratic formula
Below is an example where a proof is shown for the quadratic formula:
Let a, b, and c be real number. The solutions of
can be defined as:
Proof
Proof. In order to prove the quadratic formula, we use the process of completing the square. Starting with
arithmetic gives us
The above proof serves as a stress test of some kind, rendering multiple complex and nested equations. The TeX syntax for this proof is taken from a public template on OverLeaf [4].
References
- [1] https://github.blog/2022-05-19-math-support-in-markdown/
- [2] https://www.tug.org/
- [3] https://docs.github.com/en/get-started/writing-on-github/working-with-advanced-formatting/writing-mathematical-expressions
- [4] https://www.overleaf.com/articles/the-quadratic-formula/wprdthgttvzm