# Incorrect value of Pi in Lua after 16th Decimal Place

The following is the code.

\documentclass{article}
\usepackage{luacode}
\begin{document}
\luaexec{tex.sprint(string.format('\%.20f', math.pi))}
\end{document}


It gives the output as

3.14159265358979311600

It can easily be seen that the value of pi goes on incorrect. Compare here. The correct value up to 20 decimal places is

3.14159265358979323846

This has nothing to do with luaTeX or luacode because one gets same answer in lua. It has something to do how lua calculates value of pi. Is there a way to get correct value of pi in luaTeX or lua ?

From the Lua manual, section 2.1

Standard Lua uses 64-bit integers and double-precision (64-bit) floats, but you can also compile Lua so that it uses 32-bit integers and/or single-precision (32-bit) floats. The option with 32 bits for both integers and floats is particularly attractive for small machines and embedded systems.

With double precision, you can't expect more than 15 exact decimal digits, see https://en.wikipedia.org/wiki/IEEE_754#Basic_and_interchange_formats

• Thanks for your answer. Could you please tell how to do it precisely in LaTeX? – user61681 Apr 23 at 10:34
• @user61681 What do you mean? LaTeX has no float type. Exploiting expl3 facilities you get double precision just like for Lua. – egreg Apr 23 at 10:46
• I mean this : Can I get precise value of pi up to 20 decimal places using lua in LaTeX document? Yes or No. If yes, with what command? – user61681 Apr 23 at 11:05
• @user61681, just hardcode the value you want for pi. It doesn't need to be from a package because it's not a calculated value, and it's not something that might change in a future update. Pi is pi, so just hardcode the 40-50 digits you want. Also note that the level precision you are after is usually meaningless (only matters in a few rare cases). – JPhi1618 Apr 24 at 14:41

You can cheat and do this using Metapost via the luamplib package.

\documentclass{article}
\usepackage{luamplib}
\mplibtextextlabel{enable}
\mplibnumbersystem{decimal}
\begin{document}
This is $\pi$:
\begin{mplibcode}
vardef getpi =
numeric lasts, t, s, n, na, d, da;
lasts=0; s=t=3; n=1; na=0; d=0; da=24;
forever:
exitif lasts=s;
lasts := s;
n := n+na; na := na+8;
d := d+da; da := da+32;
t := t*n/d;
s := s+t;
endfor
s
enddef;
beginfig(1);
draw textext(decimal getpi);
endfig;
\end{mplibcode}
\end{document}


But I think it might be easier just to write the digits out by hand!