Take the 2-minute tour ×
TeX - LaTeX Stack Exchange is a question and answer site for users of TeX, LaTeX, ConTeXt, and related typesetting systems. It's 100% free, no registration required.

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?

share|improve this question
    
you want the code to do the calculation? –  Yiannis Lazarides May 22 '12 at 14:30
    
@YiannisLazarides: I want to pass in the final value to includegraphics' viewport. –  cyanide-based food May 22 '12 at 14:32
    
I don't think that calc is able to do sums with floating point numbers. –  egreg May 22 '12 at 14:34

2 Answers 2

up vote 4 down vote accepted

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}
share|improve this answer
    
Please wait, I will pass in the final value to viewport. I hope there is no problem. –  cyanide-based food May 22 '12 at 14:41
    
@Guaranteed for seven years:) –  Yiannis Lazarides May 22 '12 at 14:41
1  
@Forgiver Just remember to enclose \temp or \unit in braces: viewport=0 0 {\temp} {\temp} –  egreg May 22 '12 at 14:46
    
@egreg: Can I use \space instead of {}? –  cyanide-based food May 22 '12 at 14:47
    
@Forgiver I don't think so. –  egreg May 22 '12 at 14:48

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>}
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.