5

I want to do the following arithmetic:

(x-y)*unit/s where x, y, s are rational constants and unit is in length unit.

\documentclass{article}
\usepackage{calc}
\newlength\unit
\unit=16pt
\def\x{0.5}
\def\y{0.3}
\def\s{0.8}

\newlength\temp
\begin{document}
\temp=\unit/\real{\s}*(\real{\x}-\real{\y})\relax
\the\temp
\end{document}

What is the easiest way to write dimensional expression?

3
  • you want the code to do the calculation?
    – yannisl
    May 22, 2012 at 14:30
  • @YiannisLazarides: I want to pass in the final value to includegraphics' viewport. May 22, 2012 at 14:32
  • I don't think that calc is able to do sums with floating point numbers.
    – egreg
    May 22, 2012 at 14:34

2 Answers 2

4

To be honest the easiest way is to calculate it using PGF.

\documentclass{article}
\usepackage[demo]{graphics}
\usepackage{pgf}
\newlength\unit
\unit=16pt
\def\x{0.5}
\def\y{0.3}
\def\s{0.8}
\newlength\temp
\begin{document}
\makeatletter
\pgfmathsetlength{\temp}{\unit/\s*(\x-\y)}
\the\temp
\includegraphics[width=\temp]{test}
\end{document}

enter image description here

If you pass it to \includegraphics, always better as a macro parameter.

 \def\putgraphic#1{%
   \includegraphics[viewport=#1 10 20 20]{test.png}}
 \putgraphic{\temp}
6
  • Please wait, I will pass in the final value to viewport. I hope there is no problem. May 22, 2012 at 14:41
  • @Guaranteed for seven years:)
    – yannisl
    May 22, 2012 at 14:41
  • 1
    @Forgiver Just remember to enclose \temp or \unit in braces: viewport=0 0 {\temp} {\temp}
    – egreg
    May 22, 2012 at 14:46
  • @egreg: Can I use \space instead of {}? May 22, 2012 at 14:47
  • @Forgiver I don't think so.
    – egreg
    May 22, 2012 at 14:48
4

Here's with expl3 and the fp module (not the expandable version):

\documentclass{article}
\usepackage{xparse}
\ExplSyntaxOn
\fp_new:N \l_forgiver_factor_fp
\NewDocumentCommand{\xys}{ O{\funit} m m m }
 {
  \fp_set:Nn \l_forgiver_factor_fp { #2 }
  \fp_sub:Nn \l_forgiver_factor_fp { #3 }
  \fp_div:Nn \l_forgiver_factor_fp { #4 }
  #1 = \fp_use:N \l_forgiver_factor_fp #1
 }

\ExplSyntaxOff
\newlength\funit
\setlength\funit{16pt}

\begin{document}   
\xys{3.125}{2.175}{2.5}\the\funit
\end{document}

This will output

6.08008pt

that complies from echo "16*(3.125-2.175)/2.5" | bc -l, which actually prints

6.08000000000000000000

You can set other lengths by calling

\xyz[\mylen]{<x>}{<y>}{<s>}

You must log in to answer this question.

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