9

I would like to specify the width of an image as a fraction of a predefined length, like this:

\documentclass{article}
\usepackage[demo]{graphicx}
\begin{document}
    \includegraphics[width=1/3*\textwidth]{}
\end{document}

However, this doesn't work:

Illegal unit of measure (pt inserted). \includegraphics[width=1/3*\textwidth]{}
azetina
  • 28,884

2 Answers2

13

Informally, length calculation are done using factor multiplication as there is no division notation. Since any division can be represented as some multiplication, this shouldn't be a problem. So, .5\textwidth refers to half (1/2) of \textwidth, while 2\wd0 refers to twice the width of box 0. In your case it suffices to use

\includegraphics[width=0.3333\textwidth]{<img>}

You can perform all kinds of calculations using calc or even LaTeX3:

enter image description here

\documentclass{article}

\usepackage{xparse}
\ExplSyntaxOn
\cs_new_eq:NN \calc \fp_eval:n
\ExplSyntaxOff

\begin{document}

\newlength{\mylen}
\setlength{\mylen}{\textwidth}

\verb|\mylen|: \the\mylen

\setlength{\mylen}{\calc{1/3}\textwidth}
\verb|1/3\mylen|: \the\mylen

\end{document}

The LaTeX3 syntax above makes \calc an new control sequence (or macro) that is equivalent to \fp_eval:n - a floating point function that evaluates it's argument using the regular programming arithmetic (like +, -, *, /, ^, ...) taking a single argument.

Werner
  • 603,163
  • 4
    You should shed some light into the LaTeX3 syntax for the other users who might not know the construct of LaTeX3 code. – azetina Jun 21 '16 at 00:12
  • thank you for this lightening of the LATEX3 syntax, it's scary at first. – rpapa Jun 21 '16 at 06:24
4

Compile with lualatex

Mathematica graphics

\documentclass{article}
\usepackage[demo]{graphicx}
\usepackage{luacode}
\begin{document}

\newcommand\w{\directlua{tex.sprint(1/3)}}

This is my graph, it has width of \w and it looks very nice

\includegraphics[width=\w\textwidth]{}

\end{document}
Nasser
  • 20,220