Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
4

aaaaaahhhhhhh, Why does my for loop only go up to 0.99? [closed]

Asked by 6 years ago
Edited 6 years ago
for i = 0,1,0.01 do print(i) end

IT only prints up to .99 and idk why, I put this code in the command bar and it prints to .99 aswell

1
This is normal take a look at http://wiki-origin.roblox.com/index.php?title=Lua_errors Tricky Mistakes. User#5423 17 — 6y
0
I think that's because that essentially is this in c language: for(int i = 0,i < 1,i += 0.01){ } theking48989987 2147 — 6y
0
but how do i evade this effect i want it to end at 1 HilyrHere 79 — 6y
0
you could add a line like if i >= 1 then break Vulkarin 581 — 6y

Locked by User#19524

This question has been locked to preserve its current state and prevent spam and unwanted comments and answers.

Why was this question closed?

2 answers

Log in to vote
3
Answered by
ozzyDrive 670 Moderation Voter
6 years ago

The issue is caused by floating point precision error. Due to the 100 addition operations you're doing, the binary value loses precision as it has a finite length and the bit-representation gets too long.

You can see the 0.99 you're getting is not exactly 0.99 with this piece of code:

for i = 0, 1, 0.01 do
    print(i == 0.99)
end

It is generally considered a bad practice to use decimals in for loops due to this very issue. A way better idea is to simply use integers and divide them back into the decimal form if necessary:

for i = 0, 100 do
    i = i / 100
    print(i)
end
Ad
Log in to vote
2
Answered by
thesit123 509 Moderation Voter
6 years ago

It might be a simple fix. Either:

  • Add 1 to your i variable if you aren't going to be using 0
for i = 0, 1, 0.01 do
    print(i + 1)
end
  • Or instead of 1, put 1.01 if you are going to use 0
for i = 0, 1.01, 0.01 do
    print(i)
end
0
add .01, not 1 User#22604 1 — 6y