Как сравнивать double в c
Перейти к содержимому

Как сравнивать double в c

  • автор:

Научный форум dxdy

Всё работало отлично, пока не пришлось работать с физическими величинами в мелком масштабе (порядок величины в единицах СИ — $10^<-6>$» />). Такие переменные пришлось сравнивать с нулём по-другому</p>
<p>Относительная погрешность <img decoding=и абсолютная погрешность $\Delta$при известной величине $v$связаны между собой как $\varepsilon=\Delta/v,$$\Delta=\varepsilon v.$

Так что, когда вам надо найти, что числа равны с заданной погрешностью, $\lvert a-b\rvert\leqslant\Delta,$то вы оцениваете $\Delta=\max\<\Delta_a,\Delta_b\>,$» /> где <img decoding=$\Delta_b=\varepsilon b.$

В принципе, выбор наибольшей $\Delta$— стандартная процедура — в данном случае перестраховка, поскольку если две величины будут различаться по порядку величины, то и между собой они равны не будут. С другой стороны, она обеспечивает хотя бы коммутативность отношения: $a\approx b\Leftrightarrow b\approx a,$хотя уже ни о какой транзитивности речь не идёт.

И совет на будущее: никогда не полагайтесь на сравнения с погрешностью DBL_EPSILON . Если у вас есть два числа, которые надо сравнить, то они откуда-то происходят, из каких-то измерений или расчётов, и их погрешность всегда выше, чем DBL_EPSILON . Правильно в таком случае использовать погрешность вычислений или измерений, которую вы оцениваете или сами, или требуете от того, кто предоставляет вам сами числа.

Последний раз редактировалось hurtsy 12.12.2011, 18:21, всего редактировалось 1 раз.

Comparing double values in C#

What’s the reason behind this? Can you suggest a solution for this?

Vadim Ovchinnikov's user avatar

18 Answers 18

It’s a standard problem due to how the computer stores floating point values. Search here for «floating point problem» and you’ll find tons of information.

In short – a float/double can’t store 0.1 precisely. It will always be a little off.

You can try using the decimal type which stores numbers in decimal notation. Thus 0.1 will be representable precisely.

You wanted to know the reason:

Float/double are stored as binary fractions, not decimal fractions. To illustrate:

12.34 in decimal notation (what we use) means

The computer stores floating point numbers in the same way, except it uses base 2 : 10.01 means

Now, you probably know that there are some numbers that cannot be represented fully with our decimal notation. For example, 1/3 in decimal notation is 0.3333333… . The same thing happens in binary notation, except that the numbers that cannot be represented precisely are different. Among them is the number 1/10 . In binary notation that is 0.000110011001100… .

Since the binary notation cannot store it precisely, it is stored in a rounded-off way. Hence your problem.

Vadim Ovchinnikov's user avatar

Vilx-'s user avatar

0.01), then this could be "expected". 🙂

double and Double are the same ( double is an alias for Double ) and can be used interchangeably.

The problem with comparing a double with another value is that doubles are approximate values, not exact values. So when you set x to 0.1 it may in reality be stored as 0.100000001 or something like that.

Instead of checking for equality, you should check that the difference is less than a defined minimum difference (tolerance). Something like:

You need a combination of Math.Abs on X-Y and a value to compare with.

You can use following Extension method approach

Since you rarely call methods on double except ToString I believe its pretty safe extension.

Then you can compare x and y like

Comparing floating point number can’t always be done precisely because of rounding. To compare

the computer really compares

Result of sybtraction can not always be represeted precisely because of how floating point number are represented on the machine. Therefore you get some nonzero value and the condition evaluates to false .

To overcome this compare

Precision in Comparisons The Equals method should be used with caution, because two apparently equivalent values can be unequal due to the differing precision of the two values. The following example reports that the Double value .3333 and the Double returned by dividing 1 by 3 are unequal.

Rather than comparing for equality, one recommended technique involves defining an acceptable margin of difference between two values (such as .01% of one of the values). If the absolute value of the difference between the two values is less than or equal to that margin, the difference is likely to be due to differences in precision and, therefore, the values are likely to be equal. The following example uses this technique to compare .33333 and 1/3, the two Double values that the previous code example found to be unequal.

So if you really need a double, you should use the techique described on the documentation. If you can, change it to a decimal. It’ will be slower, but you won’t have this type of problem.

How to compare two double values in C#

Get Educative’s definitive System Design Interview Handbook for free.

Overview

We use the CompareTo() method to compare two double values or objects in Ruby. Remember that a double value in C# represents a double-precision, floating-point number.

When we compare two double values, say d1 and d2 , the CompareTo() method returns an integer that is less than 1 if the latter is lesser than the former. It returns 0 if they are both equal, or just 1 if the latter is greater.

Как сравнивать double в c

Double.CompareTo Method is used to compare the current instance to a specified object or Double object. It will return an integer which shows whether the value of the current instance is greater than, less than or equal to the value of the specified object or Double object. There are 2 methods in the overload list of this method as follows:

Double.CompareTo(Double) Method

Double.CompareTo() Method is used to compare the current instance to a specified double-precision floating-point number and returns an integer which shows whether the value of this instance is less than, equal to, or greater than the value of the specified double-precision floating-point number.

Syntax:

Here, it takes a double-precision floating-point number to compare.

Return Value: This method returns a signed number indicating the relative values of this instance and value.

  • Less than zero: This instance is less than value or this instance is not a number (NaN) and value is a number.
  • Zero: This instance is equal to value or both this instance and value are not a number (NaN), PositiveInfinity, or NegativeInfinity.
  • Greater than zero: This instance is greater than value or this instance is a number and value is not a number (NaN).

Below programs illustrate the use of Double.CompareTo(Double) Method:

Example 1:

Example 2:

Double.CompareTo(Object) Method

Double.CompareTo() Method is used to compare the current instance to a specified object and returns an integer which indicates whether the value of the current instance is less than, equal to, or greater than the value of the specified object.

Syntax:

Here, it takes an object to compare, or null.

Return Value: This method returns a signed number indicating the relative values of this instance and value.

  • Less than zero: This instance is less than value or this instance is not a number (NaN) and value is a number.
  • Zero: This instance is equal to value or both this instance and value are not a number (NaN), PositiveInfinity, or NegativeInfinity.
  • Greater than zero: This instance is greater than value or this instance is a number and value is not a number (NaN).

Exception: It throws ArgumentException if value is not a Double.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *