Own mathematical function f(x)
This raises more complications than it solves, in my opinion, but here's an idea:
\documentclass{article}
\makeatletter
\newcommand{\setfunc}[4]{%
\@namedef{f@}##1{#1}%
\@namedef{f@'}##1{#2}%
\@namedef{f@''}##1{#3}%
\@namedef{f@'''}##1{#4}%
}
\def\f#1#{\@nameuse{f@#1}}
\makeatother
\begin{document}
\setfunc{\sin(#1)}{\cos(#1)}{-\sin(#1)}{-\cos(#1)}
$\f{x}$ $\f'{1}$ $\f''{\pi}$ $\f'''{\pi/2}$
\setfunc{\log(#1)+1}{}{}{}
$\f{3}$
\end{document}
If you just want the function and not the derivatives, it's much simpler:
\newcommand{\setfunc}[1]{\renewcommand\f[1]{#1}}
Full example:
\documentclass{article}
\newcommand{\f}[1]{} % initialize
\newcommand{\setfunc}[1]{\renewcommand{\f}[1]{#1}}
\begin{document}
\setfunc{\sin(#1)}
$\f{x}+\f{3}$
\setfunc{\log(#1)+1}
$\f{3}$
\end{document}
A different implementation, where you can set any name you like (but beware of not redefining already existing commands)
\documentclass{article}
\newcommand{\setfunc}[2][\f]{\def#1##1{#2}}
\begin{document}
\setfunc{\sin(#1)}
$\f{x}+\f{3}$
\setfunc[\g]{\log(#1)+1}
$\g{3}$
\end{document}
If this works generally, I just got lucky. EDITED to do derivatives.
EDITED To be more true to math mode. EDITED to allow different function names with use of optional argument (default \f
). EDITED to use more natural syntax \f(3)
rather than \f{3}
. EDITED to provide \listfunc
macro. EDITED to work with amsmath
.
Finally, EDITED to allow a more general syntax that can include primes, subscripts etc. in the function name itself.
\documentclass{article}
\usepackage{amsmath}% BREAKS ORIGINAL CODE; REQUIRES \protected@edef IN \setfunc
\makeatletter
\newcommand\setfunc[2][f]{\expandafter\protected@edef\csname#1\endcsname(##1){#2}}
\makeatother
\def\func#1(#2){\csname#1\endcsname(#2)}
\def\listfunc#1(#2){#1(#2)=\func#1(#2)}
\newcommand\x{(##1)}
\begin{document}
\setfunc{\sin\x} I can list the function: $\listfunc f(3)$\par
or I can just print out $\f(x+y)$.\par
or with a general input syntax: $\func f(x+y)$\par
\setfunc[g'_y]{\ln\x + 3\x^2} Now we can have $\listfunc g'_y(7)$\par
\medskip
Derivatives:\par
\setfunc[y]{4\x^5 - 2\x^2 +3}
\setfunc[y']{20\x^4 - 4\x}
\setfunc[y'']{80\x^3 - 4}
\setfunc[y''']{240\x^2}
\setfunc[y^{iv}]{480\x}
$\listfunc y(2)$\par
$\listfunc y'(2)$\par
$\listfunc y''(2)$\par
$\listfunc y'''(2)$\par
$\listfunc y^{iv}(2)$\par
\end{document}
NOTE: Joel noted that the method can get confused if the evaluation value itself contains a term in parentheses, for example, $\f ( \ln(a + 1.5) )$
. The workaround for this is to embrace the inner argument, such as $\f({\ln(a + 1.5)})$
or $\listfunc y''({\ln(a + 1.5)})$
.