[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: noobie question about numeric for
- From: Javier Guerra Giraldez <javier@...>
- Date: Tue, 27 Mar 2012 05:57:08 -0500
On Tue, Mar 27, 2012 at 4:40 AM, fra III <ilterzouomo@fastwebnet.it> wrote:
> iter = 0
> for x=1.0, 2.0, 0.1 do
> iter = iter + 1
> end
> print(iter) --> 10
the issue here is that 0.1 can't be expressed exactly on binary
floating point numbers, just like 1/3 can't be written exactly in
decimal fractions.
so, when you add that number ten times to 1.0, you get sligthly more
than 2.0, and finish the loop.
the solution is to never assume any exact results when using
non-integer numbers.
if you need to control the exact number of iterations, use an integer
counter, and then multiply it by a small fraction if you need to
'fake' sub-integer increments:
iter=0
for i=10,20 do
print (i/10)
iter = iter+1
end
print (iter)
--
Javier