Floats vs whole integers in a for loop?

Hi,

As part of a bigger project, I recently had to change the transparency of a part at regular intervals, which I accomplished using:

for i = 0, 1, 0.1 do
    part.Transparency += i
end

… which was working fine, until I had to validate the value of part.Transparency as 1.

I found a work around pretty easily (instead of working with floats, I used whole integers and performed arithmetic on them), but it left me wondering why floats are difficult to work with in ROBLOX.

The above code would, when told, print output not too dissimilar to:

0.1
0.2
0.30000000000000004
0.4
0.5
0.6
0.7
0.7999999999999999
0.8999999999999999
0.9999999999999999

Is there a reason that floats at a value as imprecise as this are difficult to process?

Thanks!

I’m not going to act like I know the internals of roblox/computers in general so i can’t tell you why the floats are inaccurate but here’s a fix if you want it

for i = 0,10 do
part.Transparency = i/10
end

edit: I see you already found that fix lol, completely missed the second part of this post

This extremely popular question has good answers:

tl;dr: humans use base-10 numbers, computers use base-2 numbers. They don’t always map correctly. Like how 1/3 in base-10 ends up being 0.3333333333…

3 Likes

Thanks, that’s a really useful resource that’s taught me the necessities of tolerance values in equality checks, as well as answering my main question!

I am curious though, when I run the same code in a terminal, it displays as I would expect it to (0.1 - 1 with no trailing decimals). I imagine that’s due to something simple (like Lua sorting automatically, or the CPU rounding to save memory), any ideas why?

Either way, thanks for the link! You learn something new everyday.

Depends on the terminal, but it’s probably just doing some magic behind the scenes to format the string. Non-roblox lua’s tostring function does that, I’m not sure exactly what the mechanism is.

Roblox also used to do this when calling tostring on a number, but they recently changed it so it gives you all the decimals required to exactly represent it: Behavior change: tostring() will start returning shortest precise decimal representation of numbers

Very insightful, thank you - and I appreciate the tostring rounding rabbit hole!

Amazing what you can still learn after a decade programming, cheers!