Page MenuHomeFeedback Tracker

For do loop end value behavior indeterminate for floating point step values
New, NormalPublic

Description

When using floating point step values in the for "_i" from a to b step c do {} construct (https://community.bistudio.com/wiki/for_do), end value behavior is not as expected.

for "_x" from 0.1 to 0.5 step 0.1 do {diag_log _x}

->

20:21:50 0.1
20:21:50 0.2
20:21:50 0.3
20:21:50 0.4
20:21:50 0.5
for "_x" from 0.1 to 0.6 step 0.1 do {diag_log _x}

->

20:21:53 0.1
20:21:53 0.2
20:21:53 0.3
20:21:53 0.4
20:21:53 0.5
20:21:53 0.6
for "_x" from 0.1 to 0.7 step 0.1 do {diag_log _x}

->

20:21:57 0.1
20:21:57 0.2
20:21:57 0.3
20:21:57 0.4
20:21:57 0.5
20:21:57 0.6
for "_x" from 0.1 to 0.8 step 0.1 do {diag_log _x}

->

20:22:00 0.1
20:22:00 0.2
20:22:00 0.3
20:22:00 0.4
20:22:00 0.5
20:22:00 0.6
20:22:00 0.7

Details

Severity
Major
Resolution
Open
Reproducibility
Always
Operating System
Windows 10 x64
Operating System Version
Windows 10 Pro 64-bit (10.0, Build 16299)
Category
Scripting
Steps To Reproduce
  1. Run the for do code as above
  2. See the outputs
  3. Realize there's definitely a floating point/precision error in the implementation of for do loops
Additional Information

Either floating point step values should throw a script error, or they should behave properly.

Event Timeline

batboyx2 created this task.Mar 31 2018, 2:42 AM

This behavior exists in other programming languages such as c++ and c# - those languages don't throw compiler errors. I don't think there's much here that can be done as this is just part of the implementation of the language.

"If you add 0.1 each loop, you're going to end up with cumulative errors. It is not possible to precisely store 0.1 as a floating point number, and when you repeatedly add 0.1F/D, you'll start noticing drift. If you really want to get as close as possible, use integers for the loop then divide your integer values to calculate your floats."

https://stackoverflow.com/questions/6074938/c-sharp-proper-way-to-loop-through-a-float

Voting to close.