# How to write a math parser in TeX?

TeX is not really good in calculating, so some packages and LuaTeX were developed. But none of these solutions offers symbolic/exact mathematics, so I have tried something like this:

% Plain TeX
\catcode\@=11

% add 2 rational numbers, expandable macro
\ifnum\numexpr#2*#4 < \z@
\expandafter\the\expandafter
\numexpr\expanded{%
(-#1*#4-#2*#3)/\expandafter\@gcd\expanded{%
{\the\numexpr#1*#4+#2*#3\relax}{\the\numexpr#2*#4\relax}}}\relax
/
\expandafter\the\expandafter
\numexpr\expanded{%
(-#2*#4)/\expandafter\@gcd\expanded{%
{\the\numexpr#1*#4+#2*#3\relax}{\the\numexpr#2*#4\relax}}}\relax
\else
\expandafter\the\expandafter
\numexpr\expanded{%
(#1*#4+#2*#3)/\expandafter\@gcd\expanded{%
{\the\numexpr#1*#4+#2*#3\relax}{\the\numexpr#2*#4\relax}}}\relax
/
\expandafter\the\expandafter
\numexpr\expanded{%
(#2*#4)/\expandafter\@gcd\expanded{%
{\the\numexpr#1*#4+#2*#3\relax}{\the\numexpr#2*#4\relax}}}\relax
\fi}

% helper macros:
\def\@sgn@of@int#1{%
\ifnum #1 = \z@
0%
\else
\ifnum #1 > \z@ 1 \else -1 \fi
\fi}
\def\@abs@of@int#1{\ifnum #1 < \z@ \the\numexpr-#1\relax \else \the\numexpr#1 \fi}
\def\@gcd#1#2{%
\ifnum #2 = \z@
\@abs@of@int{#1}%
\else
\expandafter\@gcd\expanded{{#2}{\the\numexpr #1-#2*(#1/#2)\relax}}
\fi}

% example
$$\@rational@add{89}{-24}{-55}{36}$$ prints -377/72 as expected

\bye


But writing \@rational@add and similar macros all the time ... :( Some packages are able to parse somthing like 3/4 + 1/3 * ... and transform it into the right macros. But I don't understand how they do it. Can someone help me?

My dream would be writing somthing like \mathexpr 8^(1/2) + 32^(1/2) which typesets 6 \sqrt2. I don't know if this is possible in TeX or LuaTeX.

• Have you looked at sagetex? it's an interface to using Sage Math which does symbolic math. – Herb Schulz Apr 26 '20 at 13:45
• Also there is some mechanism available to call Python, in which one could use sympy. – Skillmon Apr 26 '20 at 14:16
• But I have not seen any solution for Plain TeX (for Sage and Python). :( – Weißer Kater Apr 26 '20 at 14:52
• What do you mean “Plain TeX” solution? In your code you are already using eTeX extension of “expressions”, so why not just use the xint bundle (which can run under plain TeX, with eTeX extensions of course)? – Ruixi Zhang Apr 26 '20 at 21:46

As the comments above indicate, the sagetex package is worth looking into.

\documentclass{article}
\usepackage{sagetex,amsmath}
\begin{document}
$8^{1/2} + 32^{1/2}= \sage{8^(1/2)+32^(1/2)}$
or $\sage{8^(1/2)}+\sage{32^(1/2)}=\sage{8^(1/2)+32^(1/2)}$?

No difficult coding required. The sagetex` package uses the computer algebra system SAGE which is not part of your LaTeX installation. That means either SAGE should be installed on your machine or you access it using a free Cocalc account. Since installation of SAGE can be tricky for some computers, I'd recommend opening a Cocalc account. Search this site for numerous posts showing what can be done.