5

I need to do some simple calculations like these:

\documentclass[a4paper,10pt]{article}
\usepackage{tikz}
\begin{document}
\pgfmathparse{1*0.4}\pgfmathresult 

\pgfmathparse{2*0.4}\pgfmathresult

\pgfmathparse{3*0.4}\pgfmathresult

\pgfmathparse{4*0.4}\pgfmathresult 

\pgfmathparse{5*0.4}\pgfmathresult

\pgfmathparse{15*0.4}\pgfmathresult
\end{document}

etc, Say I need to do this for all the numbers between 1 and 60.

How do I get the correct results? Actually the only one that works is the first mathparse, in the remaining cases I got strange numbers.

  • This is very similar to How to solve the 10.09999 rounding problem with pgfmath? – Werner Aug 29 '13 at 19:55
  • @Werner Amongst several others, I suspect. Perhaps we need a general 'floating point arithmetic in TeX' answer. – Joseph Wright Aug 29 '13 at 19:58
  • uhm... I'm seeing the duplicates only now, sorry... – jasonf Aug 29 '13 at 20:51
  • @jasonf Don't worry: for common questions it's expected we get dupes, that's why there is a mechanism to mark them up as such – Joseph Wright Aug 29 '13 at 20:58
6

TeX is not really good at floating-point work: there are however several implementations that are available. A few examples. First, you could active the TikZ FPU code:

\documentclass[a4paper,10pt]{article}
\usepackage{tikz}
\usetikzlibrary{fpu}
\pgfkeys{/pgf/fpu,/pgf/fpu/output format=fixed}
\begin{document}
\pgfmathparse{1*0.4}\pgfmathresult 

\pgfmathparse{2*0.4}\pgfmathresult

\pgfmathparse{3*0.4}\pgfmathresult

\pgfmathparse{4*0.4}\pgfmathresult 

\pgfmathparse{5*0.4}\pgfmathresult

\pgfmathparse{15*0.4}\pgfmathresult
\end{document}

or again with TikZ you could use the fixed point code in fp:

\documentclass[a4paper,10pt]{article}
\usepackage{fp,tikz}
\usetikzlibrary{fixedpointarithmetic}
\pgfkeys{/pgf/fixed point arithmetic}
\begin{document}
\pgfmathparse{1*0.4}\pgfmathresult 

\pgfmathparse{2*0.4}\pgfmathresult

\pgfmathparse{3*0.4}\pgfmathresult

\pgfmathparse{4*0.4}\pgfmathresult 

\pgfmathparse{5*0.4}\pgfmathresult

\pgfmathparse{15*0.4}\pgfmathresult
\end{document}

Alternatively, you could use the LaTeX3 FPU:

\documentclass[a4paper,10pt]{article}
\usepackage{expl3}
\ExplSyntaxOn
  \cs_set_eq:NN \fpeval \fp_eval:n
\ExplSyntaxOff
\begin{document}
\fpeval{1*0.4} 

\fpeval{2*0.4}

\fpeval{3*0.4}

\fpeval{4*0.4} 

\fpeval{5*0.4}

\fpeval{15*0.4}
\end{document}
  • If you are using LuaTeX then a break out to Lua is another possible. – Joseph Wright Aug 29 '13 at 19:59
  • this answer is much more "on the spot" for someone searching for a simple/quick answer. There are duplicates but they involve more complex code. Probably I even saw them but failed to find the answer I was searching for. – jasonf Aug 29 '13 at 20:55

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.