# tikz, How to define a constant and then use it in drawing

For example I would like to do something like this

r=2
\begin{tikzpicture}
\draw (0,{2*r}) ellipse ({sqrt(r)} and {8/r});
\draw (0,{r}) ellipse ({sqrt(r/2)} and {4/r});
\end{tikzpicture}


Where everywhere r is seen in the above tikz commands, it is replaced by its defined value. I cannot seem to find a way to conveniently do this, I am sure I am just not looking in the right place

One option, \defining \ra:

\documentclass{article}
\usepackage{tikz}

\begin{document}

\def\ra{2}
\begin{tikzpicture}
\draw (0,{2*\ra}) ellipse ({sqrt(\ra)} and {8/\ra});
\draw (0,{\ra}) ellipse ({sqrt(\ra/2)} and {4/\ra});
\end{tikzpicture}

\end{document}


You could use instead a (La)TeX length, via \newlength, \setlength and the appropriate syntax for lengths operations but using a length register for this simple application is not really necessary.

Or go the pgf way by defining

\pgfmathsetmacro{\ra}{2}


Code:

\documentclass{article}
\usepackage{tikz}

\begin{document}

\pgfmathsetmacro{\ra}{2}
\begin{tikzpicture}
\draw (0,{2*\ra}) ellipse ({sqrt(\ra)} and {8/\ra});
\draw (0,{\ra}) ellipse ({sqrt(\ra/2)} and {4/\ra});
\end{tikzpicture}

\end{document}


You can also use pgfkeys for this.

\documentclass{article}
\usepackage{tikz}
\pgfkeys{/tikz/.cd,
ra/.store in=\ra,
ra=0   %% initial value, set to anything so that even if you don't specify a value later, it compiles
}

\begin{document}
\begin{tikzpicture}[ra=2]   %% set it here, if not set, initial value 0 is taken
\draw (0,{2*\ra}) ellipse ({sqrt(\ra)} and {8/\ra});
\draw (0,{\ra}) ellipse ({sqrt(\ra/2)} and {4/\ra});
\end{tikzpicture}

\end{document}