Page 4 of 4

Re: For-Next loop with non integer values

Posted: Wed Sep 18, 2013 9:51 pm
by charvista
You understood it correctly Krzysztof :)

I *think* that Thorium is trying to tell you that computer's floatings is not like we have learned them at school.
For example, what we see as 1.36 can in fact be 1.3599999999998 to the computer. That's why it is good practice to avoid floats whenever possible. It is not a PureBasic error, it is the general mathematical problem with fractions, and it is the same problem in all computer languages, but some languages convert them internally, which make the program running much slower and sometimes erroneously.

There exists a trick to circumvent this and that keeps the accuracy. For money currencies, we often use maximum 2 digits after the decimal point. Transform all values to integer by multiplying by 100 (1.36 * 100 = 136) and perform all calculations with integers in the format "136", and when all calculations are done, show the result divided by 100.

Re: For-Next loop with non integer values

Posted: Thu Sep 19, 2013 7:39 am
by Thorium
Yes. As long as you do calculate your values in every iteration in a while loop you get no problems. As soon as you start to increment the value and check it for a expected end result you get problems because you cant increment and compare floats that way. If you absolutly must do it, use fixed point as charvista showed.
For everything else just count with integer and calculate floats from scratch at every iteration, so no incrementation takes place.

Re: For-Next loop with non integer values

Posted: Tue Sep 24, 2013 8:32 pm
by krzysztof
Thank You very much for all explanations, but this is unclear:
Thorium wrote:...As long as you do calculate your values in every iteration in a while loop you get no problems. As soon as you start to increment the value and check it for a expected end result you get problems because you cant increment and compare floats that way
You wrote about calculating, incrementing and counting :shock: of floats. Could You please, give an example of simple (please!) codes for explanation?

Re: For-Next loop with non integer values

Posted: Tue Sep 24, 2013 9:47 pm
by BorisTheOld
krzysztof wrote:You wrote about calculating, incrementing and counting :shock: of floats. Could You please, give an example of simple (please!) codes for explanation?
Here's the problem with floats.

Code: Select all

x.d = 0.0
While x <> 1.0
  If x > 2.0
    Break
  EndIf
  x = x + 0.1
  Debug x
Wend

Re: For-Next loop with non integer values

Posted: Tue Sep 24, 2013 10:49 pm
by krzysztof
Very nice and clear example. It explains the problem. Thank You.