# Inaccurate PGF calculation?

I'm trying to implement an invoice calculation in LaTeX and using PGF as the method to do calculations. I've run into an odd problem where it seems that PGF calculates things incorrectly and I'm not sure what's causing it. Here's a minimal example:

\documentclass{standalone}

\usepackage{pgf}
\usepgflibrary{fpu}
\pgfkeys{
/pgf/fpu=true,
/pgf/number format/.cd,
precision=2,
fixed,
fixed zerofill,
use comma,
1000 sep={.}
}

\begin{document}

\pgfmathparse{(1*800050)}\pgfmathprintnumber{\pgfmathresult}

\end{document}


Why does this output 800.050,05 when it should output 800.050,00?

-
Section 54.3 of the PGF manual says “The FPU has a uniform relative precision of about 4–5 correct digits”. –  egreg Aug 13 '14 at 13:10
\pgfmathmultiply{1}{80050} gives the right answer. So the problem is not in the storage or multiplication, it is in \pgfmathparse. –  John Kormylo Aug 13 '14 at 13:57
\pgfmathparse{1*(80050)} also works. –  John Kormylo Aug 13 '14 at 13:59

I don't think you can count on eight exact digits with the fpu library; quoting the manual, section 54.3,

The FPU has a uniform relative precision of about 4–5 correct digits.

You might use the fp library of expl3 and rely on PGF for the number printing:

\documentclass[margin=2bp,varwidth]{standalone}
\usepackage{expl3}
\ExplSyntaxOn
\cs_set_eq:NN \fpeval \fp_eval:n
\ExplSyntaxOff

\usepackage{pgf}
\pgfkeys{
/pgf/number format/.cd,
precision=2,
fixed,
fixed zerofill,
use comma,
1000 sep={.}
}

\begin{document}

\pgfmathprintnumber{\fpeval{1*800050}}

\pgfmathprintnumber{\fpeval{800050/4}}

\pgfmathprintnumber{\fpeval{800050/8}}

\end{document}


-
And also, mantissa-exponent representation is not so accurate when the numbers are not relatively close to each other for some reason. –  percusse Aug 13 '14 at 13:25
@percusse You're referring to the FPU library of PGF, aren't you? –  egreg Aug 13 '14 at 13:26
Ah yes I meant fpu, sorry. –  percusse Aug 13 '14 at 13:27

If you don't mind compiling with lualatex than you can exploit the mathematical capabilities of lua:

\documentclass[border=5]{standalone}
\usepackage{pgf,pgffor}
\def\luamath#1{\edef\luamathresult{\directlua{tex.write("" .. #1)}}}
\pgfkeys{
/pgf/number format/.cd,
precision=2,
fixed,
fixed zerofill,
use comma,
1000 sep={.}
}
\begin{document}
\parbox{.75in}{
\foreach \i in {1,...,10}{
\luamath{800050/\i}\pgfmathprintnumber{\luamathresult}\\
}
}
\end{document}


-
Why the \edef here rather than \def\luamath#1{\directlua{tex.write("" .. #1)}} and \pgfmathprintnumber{\luamath{800050/\i}}? –  Joseph Wright Aug 13 '14 at 16:23
@JosephWright no reason specifically, I don't think I thought about it that much. I guess it was just "sort of" analogous to \pgfmathparse putting the result of a calculation in \pgfmathresult. –  Mark Wibrow Aug 13 '14 at 18:16