Sum Error

Blitz3D Forums/Blitz3D Programming/Sum Error

EmerGki(Posted 2006) [#1]
Please, test the following code and You'll See what happen, the programm not sum...


Global Var1# = 86134.006
Global Var2# = 0.001

While Not KeyHit(1)

Var1# = Var1# + Var2#
Print Var1#

Wend



Thank you If you can tell me something about... ;).


Tom(Posted 2006) [#2]
Looks to be a precision thing, there's more knowledgable people on these forums who could give you a technical answer (Floyd?)


RGR(Posted 2006) [#3]
.

Last edited 2012


dynaman(Posted 2006) [#4]
After RaGR let me be the second to welcome you to our friendly forums!

As for your question, Tom is correct - B3D uses single precision floating point numbers so rounding "errors" are easily noticed.


(tu) sinu(Posted 2006) [#5]
If you use strings though it is almost correct :)


H&K(Posted 2006) [#6]
EmmerGKi,

This is a common problem with all computer languages (Well all the ones Ive used).

Each digit of the number, isnt stored as a seperate value, but rather the whole number is saved as a value in base 2 (Binary)

What happens is that the number is held in a "Finite" amount of space.
So for example lets concider a BYTE, what happens when you add 2 to 254, (8 bits can give you 0 to 255), if the space alocated to the answer is only enough for 256 different numbers, as in this case, you would get 0

Imagine now that you want to store numbers between 0 and 510, we could just do it be doubleing the number represented by the byte (8bits). So 24+2 would work, but how about 24+1, we dont have a 1 anymore, the smallest number we could have is 2 (or 0 obviously)

This is what Blitz does, but with the floats. So when you have a big number, the minimum value you can add has also incresed

Obviously this means that there are some calculations that dont work. But,

1) This is the first time I thought about this for ages. That is, once you know about it, you very quickly find that you just dont do it anymore

2) There are lots of workarounds if you really need to do it. (If I come across a link Ill post it here)

What you need to do now, is rethink you project/program, and see if small numbers added to large numbers is realy needed. If it is, then you need to find/write a more exact math functions.

Normaly though its quite easy to work around it. BUT you do need to re think your approach at this stage