Math functions for loot box script not working as expected

I’m trying to calculate the chance of getting specific pets from a loot box via scripting. However, the multiplication function isn’t work as expected.
the script is relatively simple and it is as follows.

local pets = {
	"Dog",
	"Cat",
	"Rabbit",
	"Duck",
	"Raccoon",
	"Bat",
	"Dragon",
	"Serpent",
	"Pyrocat",
}
local rolls = {
	20000,
	20000,
	20000,
	15000,
	10000,
	10000,
	4500,
	499,
	1,
}
local Pet = script.Pet
local total = 0
for i = 1, #rolls do
	total += rolls[i]
end
print(total)
for i = 1, #pets do
	Pet.Value = pets[i]
	local currare = rolls[i]/total
	print(pets[i]..".."..currare)
	local rarity = currare*100
	print(pets[i]..".."..rarity)
	game.Workspace.Pets[Pet.Value].PercentChance.Value = rarity
	local clone = script.ViewportFrame:Clone()
	clone.Parent = script.Parent.Frame
end

Yes I know you can have both the roll value and the pets value in the same table, I’m not asking how to make the script more efficient, I’m asking about the multiplication function in this scenario.
So my specific problem is that everything works as expected until it reaches the serpent pet. I set the script to print out the values for its rarity after each calculation. It works fine for every other pet giving the expected values but then when I get to the serpent pet it does not give me the expected values.
Screen Shot 2022-02-05 at 4.53.05 PM
Looking at the output it appears to be something with the multiplication function. Is this a bug or am I doing something wrong? I suspect I’ll probably have to change the code to just divide everything by 1,000 instead of dividing everything by 100,000 and multiplying it by 100 to get this fixed. I just found it weird that it only didn’t work for one value.

tl;dr: A loot box script I made isn’t working for just one value. It appears to be the multiplication function that messes up the number. I’m not looking to make my script work faster or be more efficient, I’m just curious why this is happening.

Edit: Can’t post this to #bug-reports:studio-bugs because I’m not a regular.

3 Likes

So apparently this has something to do with floats. In the end I did just divide the total by 100 before I divided the roll by the total and that fixed everything.

That’s caused by floating point precision errors (which occur when the available amount of bits cannot accurately represent the number), to combat this you can round each result to 2/3 decimal places by multiplying the number by 100/1000, rounding the result to the nearest integer and then dividing the result by 100/1000.

1 Like