11

I was trying to output the positive integer powers of 2 starting from 2^10=1024. I was met with a Dimension too large error. When I force compiled, every number from 2^14=16384 was output as 16383. My guess is that 16384 is just beyond the default range of numbers covered by the engine and overflows raised an error. What can I do to enable computation of bigger numbers? In 2022 16383 is no where near enough.

\documentclass{article}
\usepackage{tikz}
\begin{document}

\begin{tikzpicture} \foreach \i in {10,...,20} { \node at (\i,0) {\pgfmathprint{int(2^\i)}}; } \end{tikzpicture}

\end{document}

ded4943
  • 111

4 Answers4

10

You could use the bigintcalc package (might take some time though for very large exponents).

\documentclass{article}
\usepackage{bigintcalc}
\begin{document}
\bigintcalcPow{2}{999}
\end{document}

produces:

enter image description here

(the number is a bit too big to fit the page...)

Skillmon
  • 60,462
8

Use a mathematical engine different from the pgfmath one, which is a fixed point system with the limits you discovered (BTW, it's documented in the manual).

For example, you can use the LaTeX3 engine (floating point, IEEE 754, so you have to take into account the accuracy):

\documentclass{article}
\usepackage{tikz}
\usepackage{xfp}% not needed in recent LaTeX, thanks @egreg!
\begin{document}

\begin{tikzpicture} \foreach \i in {10,...,30} { \node at (0,0.5\i) {\fpeval{2*\i}}; } \end{tikzpicture}

\end{document}

enter image description here

Rmano
  • 40,848
  • 3
  • 64
  • 125
7

If you're free to use LuaLaTeX, the entire Lua math library is at your service.

\documentclass{article}
\begin{document}
\directlua{
  for i = 10,50 do
    tex.print ( i .. '\\ ' .. math.floor(2^i) .. '\\par')
  end
}
\end{document}

Because Lua treats \ (backslash) as the main escape character, it's necessarty to input \\ to force a single backslash character to be passed to LaTeX.

Aside: If the sole purpose of the exercise is to compute powers of 2, starting with 2^{10}, the Lua code could be made a bit more efficient, by performing multiplication instead of exponentiation in each round of the for loop:

j = math.floor(2^9)  % initialize 'j' as 2^(10-1)
for i = 10,50 do
  j = 2*j
  tex.print ( i .. '\\ ' .. j .. '\\par')
end

The first fifteen rows of the resulting output are:

enter image description here

Mico
  • 506,678
7

There are macro packages which implement better arithmetic. For example apnum.tex implements arbitrary large numbers in arbitrary precision. This macro package is implemented using only classical TeX primitives. See texdoc apnum.

You can try:

\input apnum

\newcount\tmpnum \tmpnum=1 \def\A{2} \loop \the\tmpnum: \A \par \ifnum\tmpnum<100 \advance\tmpnum by1 \evaldef\A{2*\A} \repeat

wipet
  • 74,238