lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


Dirk Laurie <dirk.laurie@gmail.com> wrote:

> A for loop with floating-point increment, and what appears to be an
> integer multiple of it as upper limit, is obscene code. In a numerical
> analysis course, it is a standard example of what one should not do,
> and a fix is taught. (It basically involves adding half the increment
> to the upper limit.)

The loop in question was all floating point values:

for i=1.0,16.0,3.2 do ... end

My issue was with the floating point math to check if the step value was the
same after trying to adjust the inital and limit values. However, due to the
nature of floating point values my initial attempt did not work (3.2 !=
3.19999999999...) but making the test simpler does seem to have worked!


> I know only one language that on a routine basis accepts that its
> users may not know all that, and therefore provides a built-in fix for
> the problem. I won't mention its name since it is a language that
> people either love or hate.

Well, now I have to ask... what language?


> If the same idea is implemented in Lua, it
> would involve two additional predefined constants math.abstol and
> math.reltol. A floating-point loop 'for x in start,stop,inc' would
> be equivalent to
> ... [snip] ...
> The defaults are such that loops like "for x=1,5,0.1" give the
> intuitively expected behaviour, but the user is permitted to change
> either tolerance. Most commonly one would set one of them to 0, so
> that the test simplifies to either relative or absolute tolerance.

What do these tolerance values actually do from a code perspective? I was
wondering if there was a way to do what I believe you are talking about,
however, I don't think it was necessary for the simple detection test I
came up with... unless you are saying there is an issue?


> I guess that the bottom line is that the VM instruction should right
> at the start determine whether integer or floating-point arithmetic is
> to be used, and that different algorithms coping with the different
> problems (integer overflow, floating-point inexactness) shoukd be
> applied.

The VM *does* make that determination, if the initial and step value are
integers and the limit value is also an integer then you get an integer
loop... otherwise, it tries to convert everything to floats, if that doesn't
work it errors out. With my patch if the loop is to be floating-point then
one final test is done to ensure the step magnitude will actually affect the
loop iterator value to prevent an infinite loop situation.

~Paige