How to implement decimal RNG like in Item Factory?

I’m trying to make a decimal RNG but it seems to bug out and go into the negatives. If anyone can help me in this, it would greatly help.

Code:

function ChanceRoll(luck: number)
	luck = luck or 1
	local totalWeight = 0
	for _, v in Auras do
		totalWeight += 1 / v.OneIn
	end
	local chance = (Random.new():NextNumber() * totalWeight) / luck
	if chance > totalWeight then chance = totalWeight end
	local counter = 0
	for _, v in Auras do
		counter += 1 / v.OneIn
		if chance <= counter then
			print(chance)
			return v
		end
	end
end
-- How to get RNG: 1 / chance
1 Like

I suggest clamping your chance value.

From:

local chance = (Random.new():NextNumber() * totalWeight) / luck
if chance > totalWeight then chance = totalWeight end

To:

local chance = Random.new():NextNumber() * totalWeight / luck
if chance > totalWeight then
    chance = totalWeight
elseif chance <= 0 then
    chance = 0
end

From what I’m seeing in your code, there should be no variables affecting anything that should make your chance negative. Although if your problem still persists, you should check out the stuff I listed below.

Possible Problems causing it to go negative:
• Luck variable from function call being negative
• Aura Onein being negative

How to find out the problem if it still happens:
• Debug every variable in play

1 Like
local chance = math.clamp(Random.new():NextNumber() * totalWeight / luck, 0, totalWeight)
-- this works, but i'm looking for a solution to make the decimal rng system
-- sorry for late response
1 Like
-- Found solution.
-- For those in the future, this is the code:
local chance = 1 / (((1 / (Random.new():NextNumber() / luck)) - luck) * totalWeight)
1 Like