In my document I have the need to do a little bit of maths, which is related to sizing images. Specifically I need a linear interpolation function, the inverse function of linear interpolation, and a clamping function.
I have constructed these functions, as well as a document to test them:
\documentclass[twoside]{memoir}
\usepackage[papersize={8.5in,11in}, vmargin=0.5in, outer=1in, inner=0.5in, includehead, includefoot]{geometry}
\usepackage{fp}
\makeatletter
\newcommand\clamp[3] {
\def\clamped{#1}
\ifdim #1pt>#3pt
\def\clamped{#3}
\fi
\ifdim #1pt<#2pt
\def\clamped{#2}
\fi
\clamped
}
\newcommand\unlerp[3] {
\FPsub\numerator{\number #1}{\number #2}
\FPsub\denominator{\number #3}{\number #2}
\FPdiv\result{\numerator}{\denominator}
\result
}
\newcommand\lerp[3] {
\FPsub\result{\number #3}{\number #2}
\FPmul\result{\number #1}{\result}
\FPadd\result{\number\numexpr #2}{\result}
\result
}
\makeatother
\begin{document}
\huge
\bfseries Clamp Tests
\normalfont
Clamp -5 between 0 and 100: \clamp{-5}{0}{100}
Clamp 45 between 0 and 100: \clamp{45}{0}{100}
Clamp 150 between 0 and 100: \clamp{150}{0}{100}
Clamp -0.5 between 0 and 1: \clamp{-0.5}{0}{1}
Clamp 0.5 between 0 and 1: \clamp{0.5}{0}{1}
Clamp 1.5 between 0 and 1: \clamp{1.5}{0}{1}
\bfseries Lerp Tests
\normalfont
Lerp 0 between 0 and 100: \lerp{0}{0}{100}
Lerp 0.5 between 0 and 100: \lerp{0.5}{0}{100}
Lerp 1 between 0 and 100: \lerp{1}{0}{100}
\bfseries Unlerp Tests
\normalfont
Unlerp 0 between 0 and 100: \unlerp{0}{0}{100}
Unlerp 45 between 0 and 100: \unlerp{45}{0}{100}
Unlerp 150 between 0 and 100: \unlerp{100}{0}{100}
Unlerp 0.5 between 0 and 2: \unlerp{0.5}{0}{2}
\bfseries Combination Tests
\normalfont
Store manual value in variable: \def\testa{0.500000000000000000}
Use manual variable in clamp: \clamp{\testa}{0}{1}
Store unlerp result in variable: \def\testb{\unlerp{50}{0}{100}}
Output unlerp result variable: \testb
%Variable -> clamp: \clamp{\testb}{0}{1}
% Fails with the following error messages:
% ! Missing number, treated as zero.
% ! Illegal unit of measure (pt inserted).
% ! Missing = inserted for \ifdim.
%Unlerp -> Clamp: \clamp{\unlerp{50}{0}{100}}{0}{1}
% Fails with the following error messages:
% ! Missing number, treated as zero.
% ! Illegal unit of measure (pt inserted).
% ! Missing = inserted for \ifdim.
\end{document}
In isolation they seem to work, but I'm having difficulty combining them. If I try to call them by nesting their arguments I get an error. I can store the output of one using \def and then display it on the page, but as soon as I try to pass it to the next command I get the same error. The failing calls can be seen at the bottom of my example, commented out.
The error I receive is:
Missing number, treated as zero.
Illegal unit of measure (pt inserted).
Missing = inserted for \ifdim.
(Plus a bunch more error messages that are repetitions of the above)
What am I doing wrong?


expl3). – Joseph Wright Oct 09 '16 at 08:27