8

Is there a reason why the code below leads to the error:

! Illegal unit of measure (pt inserted).
<to be read again> 
e
l.16 ...t [domain=-.1:.1,samples = 100] (\x,{G(\x)})

\documentclass[tikz]{standalone}
\directlua{
function G (x) 
    return (-(x^2)/3)
end
}
\pgfmathdeclarefunction{G}{1}{%
\edef\pgfmathresult{\directlua{tex.print("" .. G(#1))}}%  
}
\begin{document}
\begin{tikzpicture}
\draw [blue]  plot [domain=-.1:.1,samples = 100] (\x,{G(\x)});
\end{tikzpicture}
\end{document}
13

If you modify the function to

\pgfmathdeclarefunction{G}{1}{%
\edef\pgfmathresult{\directlua{tex.print("" .. G(#1))}}%  
\show\pgfmathresult
\edef\pgfmathresult{1}%
}

then the plot plots the (wrong:-) function without error but you get to see what you were plotting. The first few values are OK but then:

> \pgfmathresult=macro:
->-9.5052e-06.

Presumably pgf isn't expecting the e notation. Presumably lua has some number formatting functions to prevent it using that notation?

edit ah yes:

\makeatletter
\pgfmathdeclarefunction{G}{1}{%
\edef\pgfmathresult{\directlua{tex.print(string.format("\@percentchar f",G(#1)))}}%  
}
\makeatother
  • 2
    Although colossally inefficient the G function definition could be \pgfmathparse{\directlua{tex.print("" .. G(#1))}}% as the math parser can convert the e notation into something pgf can use. – Mark Wibrow Jan 24 '15 at 10:25
14

I would suggest to use Lua for all the calculations and also to create the relevant LaTeX code. Of course as Dave suggested use string.format('% .2f','number') to format the number. Two decimal places would be more than adequate for plotting.

\documentclass[tikz]{standalone}
\usepackage{luacode}
\begin{document}
\begin{luacode}
local function G (x) 
    return string.format('% .2f',-(x^2)/3)
end

tex.print('\\begin{tikzpicture}[scale=.3]')
tex.print('\\draw[color=red] (0,0)')

local z=-.1
for i=1,50 do
   tex.sprint('-- (' .. i .. ',' .. G(z)..')  ') 
   z=z+.2
end
tex.sprint(';')

tex.print('\\end{tikzpicture}')
\end{luacode}
\end{document}

This normally produces cleaner code, is easier to debug and faster. Add formatting code for axes and co-ordinates to suit your requirements. For example using the above it is trivial to also export the values as a table and also do any transformations you may want.

  • maybe it is wrong, but I prefer to separate lua and tex codes? – pluton Jan 24 '15 at 16:13
  • 1
    @pluton Getting pgf to parse numbers with four decimal places will slow you down for more complicated stuff, but use what you are comfortable with. There is no right or wrong way, just programming patterns and individual preferences. – Yiannis Lazarides Jan 24 '15 at 16:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.