56

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}}
3
  • 1
    The math capabilities of (La)TeX are rather limited. You can look at the l3fp module of expl3 (texdoc interface3), or at PGF.
    – egreg
    Dec 1, 2013 at 18:31
  • 5
    Using PGF (you need to load the tikz package), you can do the following: \newcommand\myMathFunction[1]{\pgfmathparse{5*#1 - (#1)^2}\pgfmathresult} \myMathFunction{2}.
    – jub0bs
    Dec 1, 2013 at 18:36
  • Gnuplot can be used, too: Erf function in LaTex Dec 2, 2013 at 11:42

11 Answers 11

19

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

3
  • just to clarify: only the tabular uses the l3fp code, right? the pspicture is just using its in-grained parsing and computation of algebraic expressions?
    – user4686
    Mar 14, 2014 at 22:15
  • sure, how else should it work?
    – user2478
    Mar 15, 2014 at 11:22
  • generating data which would then be plotted via the services of the pspicture. Perhaps the user has a macro which does computations not easily feasible via postscript code. For example the sum from n=x to n=x+1000 of the n th digits of π (random example, perhaps pstricks does that !!)
    – user4686
    Mar 15, 2014 at 11:35
40
+300

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}
0
33
+200

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}
4
  • 2
    I'd keep the PGFkeys call local, or at least move it outside of \myMathFunction. Dec 1, 2013 at 20:38
  • @Qrrbrbirlbel I think I'll leave it inside the definition, but I'll make it local.
    – jub0bs
    Dec 1, 2013 at 20:39
  • 1
    Instead give the options to \pgfmathprintnumber[fixed,precision=3]{...} then you don't need pgfkeys
    – percusse
    Feb 17, 2014 at 23:22
  • 1
    @percusse fixed (pun intended)
    – jub0bs
    Feb 18, 2014 at 20:12
31

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.

3
  • 3
    Probably much faster than any other approach (for if someone decided to solve Finite Elements in LeTeX...)
    – yo'
    Dec 1, 2013 at 23:17
  • @Przemyslaw This solution only works for integers, right? As far as I know, TeX's count registers only accept integers. Mar 12, 2014 at 9:42
  • 1
    @HenriMenke Yes, with restrictions as in the last sentence of my answer. Mar 12, 2014 at 19:05
25

Here's a solution using LuaLaTeX. The MWE provides a LaTeX-side macro called \MyMathFunction that interfaces with a Lua-side function called mymathfunction; the latter does the actual computations.

enter image description here

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

% Lua-side code
\begin{luacode}
   function mymathfunction( x )
      return 5*x - x^2  -- specify the function you need
   end
\end{luacode}

%TeX-side macro that invokes the Lua function
\newcommand{\MyMathFunction}[1]{%
    \ensuremath{\directlua{tex.sprint( mymathfunction ( #1 ) )}}}

\begin{document}
The value of my math function evaluated at 2 is \MyMathFunction{2}.

\newcommand\myval{6}  % macro that contains parameter value
The value of my math function evaluated at \myval\ is \MyMathFunction{\myval}.

\end{document}

Observe that the value of \myval could itself be the result of a calculation done in Lua. For example, you could execute

\newcommand\myval{ \directlua{ tex.sprint( math.exp(1) ) } }

to set \myval equal to the base of the natural logarithms. And, one could pass the result of a calculation done in Lua directly to \MyMathFunction, i.e., without setting up a macro called \myval to contain the result of the calculation. For instance,

\MyMathFunction{ \directlua{ tex.sprint( math.sqrt(2) ) }}

will evaluate \MyMathFunction at the square root of 2.

8
  • Actually, the \ifx trick was initially proposed by Herbert in his answer here. Mar 13, 2014 at 21:56
  • @HenriMenke - Thanks for this clarification, I'll edit my answer to provide the correct attribution.
    – Mico
    Mar 13, 2014 at 22:00
  • @Mico just to clarify: within the pspicture, at no point is the luacode ever executed, it is pst-plot which handles the whole thing, right?
    – user4686
    Mar 14, 2014 at 21:34
  • 2
    also, \ifx#1x appears dangerous, what if #1 is 11? shouldn't one do \ifx x#1 rather?
    – user4686
    Mar 14, 2014 at 21:37
  • 1
    @jfbu - On further investigation, you're right about the way the \ifx clause was set up in the second example (with \psplot), the "false" branch -- i.e., the part that invoked the lua code -- was never called. In consequence, I've removed the entire addendum part of the answer.
    – Mico
    Mar 15, 2014 at 14:02
18

Using PythonTeX:

\documentclass{article}
\usepackage{pythontex}

\newcommand{\MyMathFunction}[1]{\py{2*(#1)**3 - 7}}

\begin{document}
\MyMathFunction{2}
\end{document}

Suppose the above is the content of the file my_math_fun_with_python.tex.

You run LeTeX on the file:

latex my_math_fun_with_latex

then you run pythontex:

pythontex.py my_math_fun_with_latex

That will execute the python code in the file, and save the results.

Than you run LaTeX again:

latex my_math_fun_with_latex
10

The fp package provides a LaTeX2e-like interface to arithmetic:

enter image description here

\documentclass{article}
\usepackage[nomessages]{fp}% http://ctan.org/pkg/fp
\newcommand{\myMathFunction}[1]
    {\FPeval\result{trunc(((#1) * 5) - (#1)^2:0)}\result}
\begin{document}
\verb|\myMathFunction{2}|: \myMathFunction{2}
\end{document}
10

A much more general solution with the omnipotent Mathematica, LaTeX and PSTricks. In this answer I show how to

  • evaluate a function,
  • factor it into the product of linear real binomials,
  • plot its graph.

Step 1

Purchase Mathematica Home Edition (about USD $250), download and install it.

Step 2

Create a template named main.mtex (for example). The extension .mtex is important because Mathematica uses "convention over configuration" philosophy.

% main.mtex
\documentclass[preview,border=12pt,12pt]{standalone}
\usepackage{amsmath}
\usepackage{pst-plot}
\usepackage{verbatim}
\begin{comment}
<* 
    f[x_] := x^2 - 5 x + 6;
    rep:= x_Times -> Infix[x, "*"];
*>
\end{comment}


\begin{document}
\section*{Problem}
Let $ y = f(x) = <* f[x] *>$,
\begin{enumerate}
    \item factor $f(x)$
    \item evaluate $f(\tfrac 1 2)$
    \item plot its graph.
\end{enumerate}

\section*{Solution}
\begin{enumerate}
    \item $f(x) = <* Factor[f[x]] *>$
    \item $f(\tfrac 1 2)= <* f[1/2] *> $
    \item \hspace{20pt}
    \begin{pspicture}(0,-1)(5,3)
        \psaxes{->}(0,0)(0,-1)(4.5,2.5)[$x$,0][$y$,90]
        \psplot[algebraic,linecolor=blue]{1}{4}{<* f[x] /. rep *>}
    \end{pspicture}
\end{enumerate}

\end{document}

Everything in <* ... *> contains Mathematica commands and they will be replaced by invoking Splice function that will be explained shortly.

Step 3

Create an new Mathematica document named Splicer.nb (for example) as follows.

Splice["C:\\Users\\Donut E. Knot\\Documents\\main.mtex"];

And execute the command by pressing Shift+Enter. Mathematica will generate a file main.tex containing code as follows.

% main.tex
\documentclass[preview,border=12pt,12pt]{standalone}
\usepackage{amsmath}
\usepackage{pst-plot}
\usepackage{verbatim}
\begin{comment}
\text{Null}
\end{comment}


\begin{document}
\section*{Problem}
Let $ y = f(x) = x^2-5 x+6$,
\begin{enumerate}
    \item factor $f(x)$
    \item evaluate $f(\tfrac 1 2)$
    \item plot its graph.
\end{enumerate}

\section*{Solution}
\begin{enumerate}
    \item $f(x) = (x-3) (x-2)$
    \item $f(\tfrac 1 2)= \frac{15}{4} $
    \item \hspace{20pt}
    \begin{pspicture}(0,-1)(5,3)
        \psaxes{->}(0,0)(0,-1)(4.5,2.5)[$x$,0][$y$,90]
        \psplot[algebraic,linecolor=blue]{1}{4}{x^2+-5*x+6}
    \end{pspicture}
\end{enumerate}

\end{document}

Step 4

Compile the main.tex with latex-dvips-ps2pdf as it contains PSTricks code. The output is...

enter image description here

Step 5

Done. :-)

6
  • f[x]//Factor seems to be more readable. Dec 2, 2013 at 7:30
  • Have you heard of Sweave? (Suggesting because 250 is a bit steep for some of us...) It would essentially provide the free alternative to this. Statistics and mathematics calculations embedded in LaTeX
    – EricR
    Dec 3, 2013 at 21:28
  • @EricR: The spent money does mean nothing when considering the power of Mathematica. I don't think Sweave can be used to substitute for Mathematica. :-) Dec 3, 2013 at 21:43
  • I want to grant 100 bounties of 500 each to this answer. I really love it very very much. Dec 4, 2013 at 12:55
  • 1
    Just to check if you deserve your 100x500 bounties: does the pspicture really use the mathematica evaluations or rather, like I believe is the case with other answers here including a pst-plot, the pspicture is done simply by pstricks? ah, sorry, I see that yours does not differ from the others in that respect. The point is: I read the OP as how does one get a plot of a function which pstricks is unable to compute
    – user4686
    Mar 14, 2014 at 22:21
9

My package 'calculus' (installed together with 'calculator') defines some commands to declare mathematical functions. Unfortunately these functions can not be drawn using PSTricks, but you can draw it using my package 'xpicture".

Your example can be defined typing

\newqpoly{\myMathFunction}{0}{5}{-1}

(this declare the quadratic polynomial p(x)=0+5x-x^2). Then, you can compute this function and its derivative at x=2 by typing

\myMathFunction{2}{\sol}{\Dsol}

(\sol stores p(2); \Dsol stores p'(2)). Try

If $p(x)=-x^2+5x$, then $p(2)=\sol$ and $p'(2)=\Dsol$.

This code draw the graph:

\setlength{\unitlength}{0.75cm}
\begin{Picture}(-0.5,-10.5)(6.5,10.5)
   \cartesianaxes(0,-10)(\numberTWOPI,7)
   \PlotFunction{\myMathFunction}{0}{\numberTWOPI}
\end{Picture}

Function graph

1
7

Another solution with Maxima, a free computer algebra system. Note: Only for Windows users.

Step 1

Download and install Maxima.

Step 2

Create a batch file named cas.bat (for example) as follows.

rem cas.bat
echo off
set PATH=%PATH%;"C:\Program Files (x86)\Maxima-5.31.2\bin"
maxima --very-quiet -r %1 > solution.tex

Save the batch in the same directory in which your input file below exists. It is just for the sake of simplicity.

Step 3

Create the input file named main.tex (for example) as follows.

% main.tex
\documentclass[preview,border=12pt,12pt]{standalone}
\usepackage{amsmath}

\def\f(#1){(#1)^2-5*(#1)+6}


\begin{document} 

\section{Problem}
Evaluate $\f(x)$ for $x=\frac 1 2$.

\section{Solution}
\immediate\write18{cas "x: 1/2\string$ tex(\f(x))\string$"}

\input{solution}

\end{document}

Step 4

Compile the input file with pdflatex -shell-escape main and you will get a nice output as follows.

enter image description here

Miscellaneous

Apparently the output of Maxima is as follows.

solution.tex
$${{15}\over{4}}$$
0
6

For an expression with the basic operations and the square root extraction [and also logic operators and conditional evaluation] you can use \xintNewExpr or \xintNewFloatExpr from the xintexpr package to create a (completely expandable) mathematical function.

The package core routines compute exactly, with an arbitrary number of digits, and natively with fractions too. The floating point routines compute with a user-specified precision. Default is with 16 digits.

The main limitation at the time of writing is that currently sqrt is the only non-rational operation permitted. Powers must be with integral exponents.

Macros defined via \xintNewExpr or \xintNewFloatExpr may be nested one within the other. This feature was broken from release 1.09i to release 1.09ka, version 1.09kb [just released at the time of writing] reverted the bug which had been introduced in 1.09i.

\documentclass{article}
\usepackage[margin=1cm]{geometry}
\usepackage{xintexpr}
\xintNewExpr \MathFunction [1] {#1 * 5 - #1^2}

\xintNewExpr \MathFunctionRounded [1] {round(#1*5 - #1^2,12)}

\xintNewExpr \MathFunctionRoundedBis [2] {round(#1*5 - #1^2,#2)}

\xintNewFloatExpr \MathFunctionFloat [1] {#1 * 5 - #1^2}

\begin{document}\thispagestyle{empty}
\begin{verbatim}
\xintNewExpr \MathFunction [1] {#1 * 5 - #1^2}
\xintNewExpr \MathFunctionRounded [1] {round(#1*5 - #1^2,12)}
\xintNewExpr \MathFunctionRoundedBis [2] {round(#1*5 - #1^2,#2)}
\xintNewFloatExpr \MathFunctionFloat [1] {#1 * 5 - #1^2}
\end{verbatim}

\ttfamily

output in xint own fraction format:\newline
\verb|\MathFunction {12344321.56789876}->|\MathFunction {12344321.56789876}

\medskip

output as a fixed point number (12 digits after decimal mark):\newline
\verb|\MathFunctionRounded {12344321.56789876}->|\MathFunctionRounded
{12344321.56789876}

\medskip

output as a fixed point number (20 digits after decimal mark):\newline
\verb|\MathFunctionRoundedBis {12344321.56789876}{20}->|\MathFunctionRoundedBis
{12344321.56789876}{20}

\medskip

floating point number (16 digits of precision by default)\newline
\verb|\MathFunctionFloat {12344321.56789876}->|\MathFunctionFloat {12344321.56789876}

\medskip

floating point number (20 digits of precision; macro need not be redefined)\newline
\verb|\xintDigits := 20;|\xintDigits := 20;\newline
\verb|\MathFunctionFloat {12344321.56789876}->|\MathFunctionFloat {12344321.56789876}


\medskip

nesting of macros:\newline
\verb|\MathFunctionFloat {\MathFunctionFloat {12344321.56789876}}->|\MathFunctionFloat {\MathFunctionFloat {12344321.56789876}}

\medskip

\noindent\verb|\MathFunction {\MathFunction {12344321.56789876}}->|\newline
\MathFunction {\MathFunction {12344321.56789876}}

\medskip

\verb|\MathFunction has meaning| \newline
\meaning\MathFunction

\end{document}

xintexpr advertisement

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .