In the comments you have proposed using a library for symbolic calculations, which I think is a good solution to this problem.
To this end, you have to download the library you linked and its dependencies. Because they are hosted on GitHub I download them using Git.
git clone https://github.com/thenumbernine/symmath-lua symmath
git clone https://github.com/thenumbernine/lua-ext ext
Then my document directory looks something like this:
.
├── ext
│ [...]
│ ├── ext.lua
│ [...]
├── symmath
│ [...]
│ ├── symmath.lua
│ [...]
└── test.tex
Then the MWE below can be used. There I have to work around three distinct bugs.
symmath
aggressively tries to use FFI to speed up complex number operations. FFI is always available in LuaTeX but only usable when shell escape is enabled, so I remove FFI when shell escape is not enabled.
The Lua package loader that is installed by lualibs
has some kind of bug which does not allow two questions marks in the package.path
. I'm not sure what is causing this, so I've reported it here: https://github.com/latex3/lualibs/issues/2
Instead I just use package.searchpath
and pass the modified path by hand without modifying package.path
.
symmath
expects Constant
to be in the global scope which is not the default.
\documentclass{article}
\usepackage{luacode}
\begin{luacode*}
-- Disable FFI without shell escape
if status.shell_escape ~= 1 then
package.loaded.ffi = nil
end
-- Work around loader bug
local file, err = package.searchpath("symmath", package.path .. ";./?/?.lua")
if not err then
package.preload["symmath"] = loadfile(file)
end
-- Load symmath
sym = require("symmath")
Constant = sym.Constant -- bug in symmath
\end{luacode*}
\begin{document}
\[ \sin\pi = \directlua{tex.sprint(tostring(sym.eval(sym.sin(sym.pi))))} \]
\[ \tan\pi/2 = \directlua{tex.sprint(tostring(sym.eval(sym.tan(sym.pi / 2))))} \]
\end{document}

tex.sprint
with a number. Always usetex.sprint(tostring(<number>))
unless you know what you are doing. – Henri Menke Apr 16 '20 at 7:54lualibs
that prevents that currently: github.com/latex3/lualibs/issues/2 – Henri Menke Apr 17 '20 at 0:14