Floatting numbers dont add right...
Blitz3D Forums/Blitz3D Programming/Floatting numbers dont add right...
| ||
Having a serious headache here and hoping someone can help me out, my appologies if this has been brought up before, i couldnt find nothing on it. Its all to do with float variables, run this simple test.... ---------------------------------------------------- v#=0 repeat v=v+0.02 cls print v until keyhit(1) end ---------------------------------------------------- why what where and how do you end up with numbers like 33.6206? any ideas of an uncomplicated way of dealing with this kind of phenomenon? |
| ||
Blitz only uses single precision floats. You get inaccuracies like that. The only solution is to not rely on adding float values like that. |
| ||
Why is easy, computers cannot store floating point numbers exactly - unless it is a half (.5, .25, .125, etc...) and blitz only uses single precision floating point. Double precision would get it closer. How to handle it. If you are only doing addition and subtraction with 2 decimal precision, store the number as integers and just show them with 2 decimal places when outputing. If you need to do multiplication it gets trickier. Another possability is to store them as floating point, but when doing condditional tests write them as x <= Y-.5 and x<Y+.5 instead of x = y (that handles the precision differences, although the .5 could vary) |
| ||
hmmm, not good, for what im doing this is an utter pain, ho hum, just need to do it the hard way, was hoping it was just something i was missing. Cheers guys. |
| ||
Here's an even more glaring example:; Puzzle about floating point: Why is size = 5000 so inaccurate? ; Short answer: Floats have 24-bit precision but 16777200 + 1 needs 25 bits. size = 500 ; Works exactly, but try 5000. sum# = 0 For i = 1 To size For j = 1 To size sum = sum + 1.0 Next Next Print " 'One at a time' sum = " + sum Print sum = 0 For i = 1 To size block# = 0.0 For j = 1 To size block = block + 1.0 Next sum = sum + block Next Print "'Block at a time' sum = " + sum WaitKey() : End In this case adding 1.0 works exactly, up to 2^24. Thereafter adding 1.0 does nothing at all because that would require 25-bit precision. Single precision floats are 24-bit. |