Floating point accuracy weirdness

1) Create New Unity Project 2) Add Cube 3) Add below script to Cube. 4) Rounding errors occur ??

What gives, where does the extra .000001 appear from, then disappears again. ?.

function Update () {

transform.position.x += 0.001;


X value/frame 0.001 0.002 0.003 0.004 0.005 0.006000001 0.007000001 0.008 0.009000001 0.01 0.011 .... ..... 0.037999999

Welcome to the world of floating-point precision issues :) This is not related to Unity specifically but to any usage of floats on computers. The way they are encoded means that not all numbers may be perfectly represented, and that will get you small, incremental errors, just as you've noticed.

I advise taking the time to read through http://en.wikipedia.org/wiki/Floating_point for a detailled explanation, but the takeaway is this:

  • don't rely on the precision of arithmetic operation on floats
  • don't compare floats by equality ( sqrt(0.1*0.1) may not be equal to 0.1 ), be tolerant to small differences
  • the further you are from 0.0, the bigger the errors will be. IIRC, around 10K you may get as much as a 0.1 error.

Cheers, Ben

Is this posible to change floating point by using some camera script in realtime?

For egsample. if camera is close the object Clipping plane near let it be 0.01 and if the camera is far away from object near property will be 1.
Please for respond

The point of floating points is that they are not 100% accurate.

I would have hoped for something slightly more accurate that 0.001 before it starts being inaccurate, I shall just have to be aware of this issue.

Thanks for the answers people.