Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare floating point numbers in Latex

Tags:

latex

tikz

pgf

I am trying to use \ifthenelse to do a floating point comparison. This is the pgf/tikz code, which works if \y is integer only, but not otherwise:

\foreach \y in {3,3.5,...,6} {
    ifthenelse{\y<3}{
        ...
    }{
        ...
    }
}
like image 836
Abhi Avatar asked Apr 20 '10 15:04

Abhi


People also ask

How do you compare two floating point numbers?

To compare two floating point values, we have to consider the precision in to the comparison. For example, if two numbers are 3.1428 and 3.1415, then they are same up to the precision 0.01, but after that, like 0.001 they are not same.

Can we use == to compare two float values?

Because comparing floats with == is problematic, it's unwise to use them as IDs; the names in your example code suggest that's what you are doing; long integers (longs) are preferred, and the de facto standard for IDs.

Does == work for floats?

In the case of floating-point numbers, the relational operator (==) does not produce correct output, this is due to the internal precision errors in rounding up floating-point numbers.

How do you test the equality of a float?

The compare() method of Float Class is a built-in method in Java that compares the two specified float values. The sign of the integer value returned is the same as that of the integer that would be returned by the function call. Parameters: The function accepts two parameters: f1: The first float value to be compared.


2 Answers

You can not use floating variables. Use dimens instead of. For example

\newdimen \y 
\y = 3.2pt
\ifdim \y < 3.45pt ... \else ... \fi
like image 175
Alexey Malistov Avatar answered Sep 20 '22 06:09

Alexey Malistov


To expand on Alexey's suggestion of using dimensions, here is some working TikZ code that I think will solve your problem:

\documentclass{article}
\usepackage{tikz}
\usepackage{ifthen}
\begin{document}
  \begin{tikzpicture}
    \foreach \y in {3,3.5,...,6} {
      \ifthenelse{\lengthtest{\y pt > 4.5pt}}{
        \node at (0,\y) {\y\ is greater than 4.5!};
      }{
        \node at (0,\y) {\y\ is less than 4.5};
      }
    }
  \end{tikzpicture}
\end{document}
like image 29
ESultanik Avatar answered Sep 21 '22 06:09

ESultanik