8

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]{}
4
  • 5
    1/3~0.33333, so use 0.33333\textwidth.
    – Werner
    Jun 20, 2016 at 23:36
  • You can use \dimexpr<calculation>\relax while invoking the calc package.
    – azetina
    Jun 20, 2016 at 23:48
  • You can also read on how to make \newlength here in TeX.SX
    – azetina
    Jun 20, 2016 at 23:55
  • I just found the calc package. {\textwidth/\real{3}} works for me. I want to use a fraction, since I have n subfigures next to each other and it's easier to read if each width is \textwidth/n. Jun 20, 2016 at 23:56

2 Answers 2

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}
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.

2
  • 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, 2016 at 0:12
  • thank you for this lightening of the LATEX3 syntax, it's scary at first.
    – rpapa
    Jun 21, 2016 at 6:24

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .