vak: (Знайка)
[personal profile] vak
#include <stdio.h>
int main ()
{
    if (-5.2 + 4.9 != -0.3) {
        printf("Oops!\n");
    }
    if (4.8 - 6.1 != -1.3) {
        printf("Oops!\n");
    }
    if (4.3 - 3.6 != 0.7) {
        printf("Oops!\n");
    }
}
Это мне надо было простенький тестик сварганить по работе, суммировать плавающие числа, а оно вон как боком выскочило.

nz

Date: 2023-01-14 23:22 (UTC)
From: [personal profile] nz

Зачем так сложно, 0.1 + 0.2 != 0.3 же.

C#

Date: 2023-01-15 00:40 (UTC)
dennisgorelik: 2020-06-13 in my home office (Default)
From: [personal profile] dennisgorelik
In C# floating point calculations are not precise too:
[TestMethod]
public void FloatingPointCheck()
{
	Assert.AreEqual(0.2, 0.1 + 0.1); // Passes
	Assert.AreEqual(3.0, 1.0 + 2.0); // Passes
	Assert.AreEqual(0.3, 0.1 + 0.2); // Fails
}
Edited Date: 2023-01-15 00:40 (UTC)

Re: C#

Date: 2023-01-15 16:01 (UTC)
dennisgorelik: 2020-06-13 in my home office (Default)
From: [personal profile] dennisgorelik
Is there a convenient way to use more precise representation?

Re: C#

Date: 2023-01-15 19:15 (UTC)
ircicq: (Default)
From: [personal profile] ircicq
Type `decimal` in many programming languages including C#
Although it is slower

Edited Date: 2023-01-15 19:15 (UTC)

Re: C#

Date: 2023-01-15 20:40 (UTC)
dennisgorelik: 2020-06-13 in my home office (Default)
From: [personal profile] dennisgorelik
Oh.
[personal profile] vak meant "data representation in computer memory" (floating-point double vs decimal).
I thought he meant representation/conversion of data to decimal string.

In any case, the primary way to deal with imprecision is not increasing precision, but replacing number equality comparison with [epsilon] range comparison.
Edited Date: 2023-01-15 20:41 (UTC)

Date: 2023-01-16 05:50 (UTC)
dennisgorelik: 2020-06-13 in my home office (Default)
From: [personal profile] dennisgorelik
> Hex literals work fine.

Hex interface is a good workaround.
But it may be hard to convince end users to use hex interface, right?