1

my question is quite simple, i want to construct a nuumberline for a homework and came up with the following code:

\begin{tikzpicture}
\draw(0,0)--(16,0);
\foreach \x/\y in {0/0,1.6/0.2,...,16.2/2.1}
\draw(\x,0.2)--(\x,-0.2) node [below] {\y};
\end{tikzpicture}

This produces the following output: enter image description here

The first two labeled values are okay, but for some reasons \y gets the values of \x (which is definetly not wanted). Also I want to get rid of the floating point unprecission. How can I fix this?

Qrrbrbirlbel
  • 119,821
Daerker
  • 13
  • 1
    Use another loop mechanism. Or use integer values to iterate. (\x can scaled easily with TikZ by many means, i.e. x=1.6cm.) And evaluate \y via, say, \pgfmathprint{\x/8}. If you're still getting bad digits, there's \pgfmathprintnumber, [tag:siunitx] or simply \fpeval{\x/8}. The most recent Q&A in the [tag:floating-point] tag you used is a good starting point for different loop mechanism (no example, though, unfortunately) and for related Q&A. – Qrrbrbirlbel Dec 01 '23 at 21:23
  • Thank you @Qrrbrbirlbel! \fpeval was exactly what I was looking for! – Daerker Dec 01 '23 at 21:37

2 Answers2

0

This code, also, give the good results:

\documentclass[tikz,border=10pt]{standalone}

\begin{document} \begin{tikzpicture}[x=1cm,y=1cm] \draw(0,0)--(16,0); \foreach \x/\y in {0/{0},1.6/{.2},3.2/{.4},4.8/{.6},6.4/{.8},8/{1.0},9.6/{1.2},11.2/{1.4},12.8/{1.6},14.4/{1.8},16/{2.0}}{% \draw(\x,.1)--(\x,-.1) node [below] {\y};} \end{tikzpicture} \end{document}

Output:

enter image description here

ADD: You can have exactly the same result following the Qrrbrbilbel's comment. I add the complete code:

\documentclass[tikz,border=10pt]{standalone}
\newcommand{\truncate}[2]{\fpeval{trunc(#1,#2)}}
\begin{document}
    \begin{tikzpicture}[x=1cm,y=1cm]
        \draw(0,0)--(16,0);
        \foreach \x in {0,1.6,...,16.1}
            \draw(\x,.1)--(\x,-.1) node [below] {\truncate{\x/8}{1}};
    \end{tikzpicture}
\end{document}
0

You get tons of errors from that code and the output isn't reliable.

Also TikZ/PGF is not great in computing floating points and it's best to use integers whenever possible. With \fpeval you overcome the weakness in floating point arithmetic.

\documentclass{article}
\usepackage{tikz}

\begin{document}

\begin{tikzpicture}[x=0.8cm] \draw(0,0)--(16,0); \foreach \y in {1,2,...,11}{ \edef\x{\fpeval{(\y-1)*1.6}} \draw(\x,0.2)--(\x,-0.2) node [below] {\x}; } \end{tikzpicture}

\end{document}

enter image description here

egreg
  • 1,121,712