Page 1 of 1
Loops in floats
Posted: Thu Dec 18, 2025 2:49 pm
by AlfaRomeo
Hi, I want to convert a routine from QB64 to PureBasic but it includes a loop with a STEP in floating point..
How I could convert this:
Code: Select all
FOR a = 0 TO 50 STEP .04
...
code
...
NEXT
Thanks in advance
Re: Loops in floats
Posted: Thu Dec 18, 2025 3:03 pm
by RASHAD
Hi
Try
Code: Select all
Define a.f
Repeat
Debug a
a.f+0.04
Until a => 50
Code: Select all
Define a.f
While a < 50.04
Debug a
a.f+0.04
Wend
Re: Loops in floats
Posted: Thu Dec 18, 2025 3:20 pm
by STARGÅTE
Please note that loops with floats are not numerically stable.
Depending on the increment value, you sometimes reach the final value and sometimes not, even if you use doubles!
Code: Select all
Define a.d, da.d
a = 0.0 : da = 0.1
While a <= 2
Debug StrD(a, 3)
a + da
Wend
Debug "---"
a = 0.0 : da = 0.2
While a <= 2
Debug StrD(a, 3)
a + da
Wend
Debug "---"
It is more stable to use:
Code: Select all
Define ia.i, a.d
For ia = 0 To 5000 Step 4 : a = ia / 100.0
; code with "a"
Next
Re: Loops in floats
Posted: Fri Dec 19, 2025 11:48 am
by AlfaRomeo
With the code:
Define ia.i, a.d
For ia =
100 To 5000 Step 4 : a = ia / 100.0
; code with "a"
Next
it worked like a charm
Thank you all
Re: Loops in floats
Posted: Fri Dec 19, 2025 1:57 pm
by jacdelad
I would prefer the RASHAD version since it avoids the division. But beside speed, both work.
Re: Loops in floats
Posted: Fri Dec 19, 2025 7:54 pm
by wilbert
jacdelad wrote: Fri Dec 19, 2025 1:57 pm
I would prefer the RASHAD version since it avoids the division. But beside speed, both work.
If the goal is to avoid division you could also do
Code: Select all
Define ia.i, a.d
For ia = 100 To 5000 Step 4 : a = ia * 0.01
; code with "a"
Next
Re: Loops in floats
Posted: Sat Dec 20, 2025 7:17 am
by jacdelad
Yes, that's good too. But RASHADs version uses an addition, this one a multiplication. I guess the addition is still a bit faster.
So many solutions for one problem, that's one of the points why I like programming.

Re: Loops in floats
Posted: Sat Dec 20, 2025 10:15 am
by STARGÅTE
jacdelad wrote: Sat Dec 20, 2025 7:17 am
I guess the addition is still a bit faster.
No, not on modern CPUs/FPUs. Nowadays, also MUL or FMUL need only a single clock cycle, similar to ADD or FADD.
But of course, adding 0.04 directly to the iteration variable is faster than iterating a dummy integer variable and then scale it.