D
D
Denis Bredun2021-06-11 23:17:40
C++ / C#
Denis Bredun, 2021-06-11 23:17:40

Why, when adding 0.001 of type float or doable 1000 times, after a few zeros after the decimal point, more numbers appear out of nowhere and how to solve it?

static void Main()
    {
      float a = 0.001f;
      for (int i = 0; i < 1000; i++)
      {
        a += 0.001f;
      }
      Console.Write(a);
    }

Output: 1.0009907
Where did the "9907" part come from, if it was supposed to be just one?
I go in steps (passes through the cycle):
1. 0.002
2. 0.003
3. 0.004
4. 0.00500000035 - that's what it is?
5. 0.00600000052 - and again
6. 0.00700000068 - and again
What is it? Why is this happening? Where do these "extra" numbers come from?
The same with double:
I thought I would get rid of the problem, because double has increased accuracy (usually it is used in calculations).
static void Main()
    {
      double a = 0.001;
      for (int i = 0; i < 1000; i++)
      {
        a += 0.001;
      }
      Console.Write(a);
    }

Output: 1.0010000000000006 I go in
steps (passes through the cycle):
1. 0.002
2. 0.003
3. 0.004
4. 0.005 - Ohhh, everything is fine here already
5. 0.006 - and here too
...
7. 0.0090000000000000011 - off we go! Again!
Why is this happening? Where do these "extra" numbers come from?
How is this related to the binary number system? (It seems that I said the correct concept, I could be wrong here)
How can this problem be solved or how can it be avoided?
How can I, for example, if after "such" addition I want to check that the number 1 came out, and such a chupacabra came out? Explicit conversion to integer type?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
J
Johnny Gat, 2021-06-11
@Luffy1

https://habr.com/ru/post/112953/

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question