[Tex/LaTex] How to define a mathematical function as a LaTeX macro

calculationspst-plotpstricks

I am attempting to create a usable function within LaTeX such that its inputs are transformed mathematically. However, I cannot find any documentation that can perform such mathematical function definition.

Here is an example of what I am seeking:

Having defined a function entitled \myMathFunction which accepts only one parameter, the follow usage:

\myMathFunction{2}

should output 6 if the function is defined as follows: ({#1} * 5) - {#1}^2

Where {#1} is the parameter, and in the case of my example, is equal to 2.

Additionally, the function should be usable within a PSTricks plot. E.g.

\psplot[
    algebraic,
    linecolor   = red,
    linewidth   = 1pt
]{0}{TwoPi}
{\myMathFunction{x}}

Best Answer

A calculated table and the plotted curve:

\documentclass{article}
\usepackage{pst-plot}
\usepackage{xparse}
\ExplSyntaxOn%% allow _ : as a letter
\newcommand\myMathFunction[1]{% 
  \ifx#1x ((#1) * 5) - (#1)^2  
  \else \fp_to_decimal:n {((#1) * 5) - (#1)^2} \fi}
\ExplSyntaxOff
\begin{document}
\begin{tabular}{ r r }
$x$ & $f(x)$ \\\hline
0 & \myMathFunction{0}\\
1 & \myMathFunction{1}\\
2 & \myMathFunction{2}\\
3.3 & \myMathFunction{3.3}\\
4 & \myMathFunction{4}\\
5 & \myMathFunction{5}\\\hline
\end{tabular}
%
\pspicture[shift=*](-1,0)(6,7)
\psaxes{->}(5.5,6)
\psplot[algebraic,linecolor=red,linewidth=1.5pt]{0}{5}{\myMathFunction{x}}
\endpspicture
\end{document}

enter image description here

Related Question