Saturday, April 16, 2022

Rendering mathematical expressions

You might want to render mathematical expressions in your JVM based applications. An obvious way to do that is to use an existing library like jlatexmath. The jlatexmath library can be integrated into your swing programs as demonstrated below.
import javax.swing.*;
import org.scilab.forge.jlatexmath.TeXConstants;
import org.scilab.forge.jlatexmath.TeXFormula;
import org.scilab.forge.jlatexmath.TeXIcon;

public class FormulaViewer {

    public static void main(String[] args) {

        var frame = new JFrame();
        frame.setSize(400, 200);

        String expr = "\\zeta(x) = \\sum_{n=1}^{\\infty} \\frac{1}{n^x}";
        TeXFormula form = new TeXFormula(expr);
        TeXIcon icon = form.createTeXIcon(TeXConstants.STYLE_DISPLAY, 40);

        frame.setTitle("Expression Viewer");
        var panel = new JPanel();
        var label = new JLabel();
        label.setIcon(icon);
        panel.add(label);

        frame.add(panel);
        frame.setVisible(true);

    }

}

Here is the Reimann zeta function displayed in a JFrame:



There is also the JEuclid project for MathML, in case you want to go that route. These established libraries solve all your rendering needs, so the only thing that remains is conversion. We need to be able to take S-expressions and convert them into Latex.

S-expression $\to$ Latex

S-expressions have always been the best way of encoding mathematical expressions for use in computer algebra, going back to Macsyma. Later computer algebra systems made minor variations on the format, but there is still a distinction between how mathematical expressions are stored and how they are rendered. A few simple conversion routines can be made to address that.

External links:
jlatexmath
jeuclid

No comments:

Post a Comment