0

I was writing this code to get random float numbers with 2 decimals at most when I realised there were some weird numbers in the console.

public void PrintNumbers()
{
   for(int i = 0; i < 30; i++)
   {
      int num = Random.Range(1, 200);
      float x = num * 0.1f;
      print(x);
   }
}

Then I realized that the number was always 8.900001 so I wrote this piece code:

public void PrintWeirdNumber()
{
    float x = 89 * 0.1f;
    print(x);
}

This method always prints 8.900001. I already found an easy solution, wich is just to divide the intenger by 10.0f instead of multiplying by 0.1f.

public void PrintNumber()
{
    float x = 89 / 10.0f;
    print(x);
}

This will always print 8.9

Why is this happening? I just don't understand float number enough to know the reason behind this. Any help?

MadJoe
  • 23
  • 1
  • 7
  • Maybe this post can give you a hint: https://stackoverflow.com/questions/3975290/produce-a-random-number-in-a-range-using-c-sharp – uvr Apr 28 '21 at 06:48
  • Some tips on how to deal with it https://softwareengineering.stackexchange.com/questions/202843/solutions-for-floating-point-rounding-errors – Caius Jard Apr 28 '21 at 06:52
  • Thanks for your answer, but i'm not trying to get help getting random float numbers, i'm trying to get help undestanding why a number divided by 10.0f gives a different result than the same number multiplied by 0.1f, and why this happens with the number 89 (1-199 range) and not another numbers. – MadJoe Apr 28 '21 at 06:56
  • @MadJoe both results are slightly off: divide by 10f = 8.8999996185302734375, times 0.1f = 8.90000057220458984375. 10f==10, 0.1f=0.10000000149 – Hans Kesting Apr 28 '21 at 07:09
  • welcome to floating point representation - 0.1 decimal can only be represented by a periodic binary number, which in turn is impossible to store in finite memory (and less so in 32 or 64 bit floating point) – yes Apr 28 '21 at 11:21
  • Thanks you all for your answers, it seems that the issue with float numbers is very deep. I'm gonna read the post suggested by Caius Jard. – MadJoe Apr 28 '21 at 16:32

0 Answers0