[Tex/LaTex] the best way to do math inside LaTeX macros

calculationsenvironmentsmacros

I'm interested in writing a little personal package (or sharing it if it's actually useful) to speed up typesetting Trigonometry. I'd like commands like

\triangle{\alpha}{\beta}{\theta}{a}{b}{c}{30}{60}{90}
%% (label angles, label sides, absolute angles) 

to draw the simple drawings that worksheets/notes need over and over. In addition, I'd like commands such as \solvedegtan{24} to display tan(24°) = 0.445 in the document.

I know I could probably accomplish this using python.sty (I've done that in the past) but what is the proper way to make LaTeX do the calculations for drawing (I'll do the actual drawing in TikZ) and solving?

Best Answer

Here's a LuaLaTeX-based method for setting up the macro \solvedegtan{24}:

enter image description here

% !TEX TS-program = lualatex
\documentclass{article}
\newcommand\solvedegtan[1]{%
    \directlua{ tex.sprint ( math.tan ( math.rad (#1) ) ) }}
\begin{document}
\solvedegtan{24}
\end{document}

When dealing with the % character, which is "special" to both TeX and Lua (but in different ways), it's possible to "escape" the percent character while using the \directlua function. However, it's generally more convenient, coding-wise, to load the luacode package and to set up separate Lua-side and TeX-side code blocks. (Within a luacode environment, only the \ (backslash) character needs to be escaped.)

The following example illustrates the operation of the string.format function, set to show 5 digits after the decimal point. (The Lua function string.format is a front end to the C function sprintf; hence, rounding is applied if necessary.)

enter image description here

% !TEX TS-program = lualatex
\documentclass{article}
\usepackage{luacode} % for 'luacode' environment

%% Lua-side code
\begin{luacode}
function solvedegtan(x,prec)
    return( tex.sprint ( 
       string.format( "%."..prec.."f", math.tan ( math.rad (x) ) ) ) )
end
\end{luacode}

%% TeX-side code
\newcommand\solvedegtan[2]{\directlua{ solvedegtan(#1,#2) }}

\begin{document}
\solvedegtan{24}{5}
\end{document}
Related Question