V
V
versidue2021-07-21 18:45:51
C++ / C#
versidue, 2021-07-21 18:45:51

Why is the value of the floating point type decremented?

0.1 in binary representation is:
0.10000000000000000555111512312578

double value = 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1;

std::cout << std::setprecision(32);
std::cout << value << "\n\n";


Why is the result 0.99999999999999988897769753748435?
After all, the number must clearly be greater than 1, not less.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
R
res2001, 2021-07-22
@versidue

Floating point numbers are approximate by definition. Each operation on similar numbers introduces its own error into the result. So don't be surprised. In which direction and how much the error will be, I think this can be calculated, but for this you need to dig deeper.
To check, you can simply print the result of 2 additions, then three, ... And also check the result of multiplication.
There are many interesting things to discover here.
It is also interesting to compare the result of the same calculations on double and float.
Do not even hope to get some exact result in floating point. If precision is needed, then a fixed point must be used.

M
maaGames, 2021-07-21
@maaGames

Apparently, because 0.1 is not 0.1 and floating point numbers don't have to do anything. Not to mention the fact that this expression could be counted during compilation by unknown numbers, or could be replaced by multiplication, or was replaced by multiplication even when the result was calculated at the time of compilation ...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question