How can I define a mathematical function as a LaTeX macro?

Remarks

I used the powerful LaTeX3 featureset l3fp, which is automatically loaded by xparse.

Implementation

\documentclass{article}
\usepackage{xparse}
\ExplSyntaxOn
\NewDocumentCommand{\myMathFunction}{m}
    { \fp_to_decimal:n {((#1) * 5) - (#1)^2} }
\ExplSyntaxOff
\begin{document}
\myMathFunction{2}
\end{document}

Here is a TikZ/PGF solution.

I'm not sure how it compares to the l3fp approach, but it definitely offers more flexibility than a low-level TeX approach because

  • it works in fixed-point arithmetic, not just with integers, and
  • by using the right PGFkeys, you can easily customise how the result should be printed (trailing zeros, scientific notation, etc.). I refer you to section 66: Number printing of the PFG manual for more details on that.

enter image description here

\documentclass{article}

\usepackage{tikz}

\begin{document}

% definiton
\newcommand\myMathFunction[1]%
{%
    \pgfmathparse{5*#1-(#1)^2}%
    \pgfmathprintnumber[fixed,precision=3]{\pgfmathresult}%
}

% macro calls
\myMathFunction{2} \quad
\myMathFunction{45} \quad
\myMathFunction{-56}

\end{document}

In good old (Plain) TeX, i.e., without LaTeX, with the proper TeX syntax:

\documentclass{article}

\begin{document}

\newcount\pom % temporary
\newcount\kw % square
\newcount\first % first

\def\myMathFunction#1{\pom#1  \first\pom \kw\pom  
\multiply\kw by\pom \multiply\first by5 
\advance\first by-\kw \the\first}

\myMathFunction{2}


And an example of loop:

\newcount\n
\n-10
\loop \ifnum\n<10 $f(\the\n)=\myMathFunction{\n}$ \advance\n by1 \repeat

\end{document}

enter image description here

We could do it using just two counters, but this solution is easier to understand. Numbers are integers, with the absolute value less than 2^31 on all stages of computing.