Lexicographical ordering of several doubles

Consider a class of double types

class path_cost {
   double length;
   double time;
};

If I want to lexicographically organize the list path_costs, I have a problem. Read on :)

If I use the exact value for the equality test like this:

bool operator<(const path_cost& rhs) const {
   if (length == rhs.length) return time < rhs.time;
   return length < rhs.length;
}

the resulting order is likely to be wrong, because a small deviation (for example, due to numerical errors in calculating the length) can lead to the failure of the length test, so, for example,

{ 231.00000000000001, 40 } < { 231.00000000000002, 10 }

erroneously executed.

If I use this tolerance as an alternative

bool operator<(const path_cost& rhs) const {
   if (std::fabs(length-rhs.length)<1-e6)) return time < rhs.time;
   return length < rhs.length;
}

then the sorting algorithm may fail terribly, because the <-operator is no longer transitive (that is, if a <b and b <c, then a <c cannot be executed)

? ? , , , , .

( , , ): :

  • A = {231.0000001200, 10}
  • B = {231.0000000500, 40}
  • C = {231.0000000100, 60}

    • A.Length B.Length 7-e7, , A < .
    • B.Length C.Length 4-e7, , B < .
    • A.Length C.Length 1.1-e6, A > .

( Esben Mose Hansen) . . , ( ;))

+3
5

?

, , , , , ?

, , "" , .

+4

, , . , , , , , a > b a = b. , , , a b , , a b a b. - :

C A B, A > B D(n) = B+n*(C/10) 0<=n<=(10*(A-B))/(C) , D (n) D (n-1) D (n + 1) , , . D (0) B D ((10 * (A-B))/(C)) = A, A B .

, - . - 10 ^ 6, int shoudl , , 1.00001 * 10 ^ -6 0.999999 * 10 ^ -6, , .

, , , , .:)

P.S. ?

+1

.

, , . , quicksort , , . ( quicksort, , .)

, , . -, - . union-find (, , ), , . , , .


, . , , , . , , .

+1

, , , . , , , , , , . .

0

100% double s. , , . ? ?

, - 1e-9. , . .

Even if this fails, it means that it is doublesimply inadequate for your purposes. This scenario is unlikely, but can occur if you need very high-precision computing. In this case, you need to use an arbitrary precision package (e.g. BigDecimal in Java or something like GMP for C). Again, select this option only when there is no other way.

0
source

Source: https://habr.com/ru/post/1754616/


All Articles