,Are floats broken or is this some precision issue?

,I’m using blueprints and I’m seeing an issue with floats.

Simple blueprint code, taking a float variable, setting it to 0 then adding 0.1 to it while it’s less than 10.

screenshot of blueprint: http://i.imgur.com/a0ubPWV.png

Results start 0.0, 0.1, 0.2, 0.3 etc, but then we get, later on, 2.6, 2.7, 2.799999 2.899999 2.999999 …

I thought at first that it was just the conversion to string messing it up, but then I added the test to show if the result is less than 5.0, and when I have added exactly enough 0.1s to make the result 5.0, it is displaying as 4.999998 and also saying “true” to “< 5.0”, so it really is not 5.0.

This is normal float behavior and has to do with the way floats are represented in computer memory. It’s commonly referred to as floating point errors, or just float errors, and as far as I know there’s not a lot you can do except keep this in mind and try to structure your code around it. For example this is the reason you should never compare a float to an exact value because it might never hit that exact value.

If you’re looking to add up a float in a looping fashion for something that is supposed to increase over time, like regenerating health, your best bet is to ignore this error and instead make sure you cap it if it goes over your limit.

On the other hand if you want a loop that runs for exactly 50 loops you’re better off using an integer to count and perhaps set the value of the float to CurrentCount / MaxCount * FloatIncreasePerLoop. So instead of continously adding up the float you recalculate it each loop.

I tried this in c++, certain that it would work in c++ but it failed in a similar way (although not at the same point) so it looks like you’re right. Thanks for your answer. Even knowing this, this is going to make it hard for me to do the work I want to do with hit location vectors.

For the sake of making your life easier, without having to go down to C++, for accuracy at higher iterations the attached Blueprint is good for:

  1. 160 iterations while adding 0.1 to 0.1
  2. 80 iterations while adding 0.2 to 0.2
  3. 40 iterations while adding 0.4 to 0.4
  4. 20 iterations while adding 0.8 to 0.8
  • the addFloat variable is where you will set your value in the tenths in your case 0.1.
  • the Float variable is set to 0 at the start.
  • Count is set to 0 at the start.
  • maxCount is set to 160 iterations for adding 0.1 see above.

I am using the Math Expression node for a clean graph, but going over the attached image it should be self explanatory what is going on.

Let me know if you need further explanation.

Thank-you.