Math.fac()/"!" operator

Currently in Lua and Rbx.Lua, it’s really hard to get the factorial of a number. Using factorials can allow ease to write probability equations.

This is what I’d have to write to get the factorial of a number-

function factorial(n)
	local r = 1
	
	for i=math.floor(n), 1, -1 do
		r = r*i
	end
	
	return r
end

Would like a math.fac() function or the “!” operator to be added in Rbx.Lua to save many people headaches when writing this math in scripts :stuck_out_tongue:

1 Like

This really isn’t necessary. There is an infinite number of cool useful functions that shouldn’t be added just for the sake of having them, like the nth Fibonacci number or nth prime. Changing Lua or bloating the math library isn’t good.

10 Likes

I’d be skeptical why many calculators including Google have the “!” operator in hand. Doesn’t seem logical why Lua doesn’t have the “!” operator too. Or at least a math function for this.

No programming language has a factorial operator. You write the function and then you can call the function whenever you need it. Google isn’t a programming language and it is supposed to be able to interpret various inputs on purpose. You can calculate a factorial by writing a function to calculate factorials and then calling that function when you need a certain factorial, just like for anything else. It’s not hard at all. In fact, a factorial function is a classic introductory example for basic programming. Creating a new language isn’t the way to go.

4 Likes

I have only ever needed factorial once. Not sure about its usefulness as a standard library function.

I still think it’d be an interesting feature nonetheless, but like you said not entirely necessary.

Hm, based on all of your thoughts on this, I believe now that this will never be added. Should this thread be closed?

Adding new operator syntax would be creating new language, so that definitely won’t happen, and adding a new standard library function that’s not commonly used also isn’t desirable, so the best you can do is define it yourself in your own scripts:

math.fac = function(n)
    local v = 1
    for i = 2, n do
        v = v * i
    end
    return v
end

Factorial is not terribly useful on its own because of how quickly it blows up. In the most common uses, for combinations ans permutations calculations (more common in card/casino game AIs than in most Roblox games), you almost never have to actually compute a full factorial. You take advantage of the facts that you have factorials in both the numerator and denominator of the expressions, and that there is cancellation either by having repeated factors, or by partially evaluating the expressions and then reducing them by their GCD, thus avoiding overflow that would occur if you computed numerator and denominator independently.

9 Likes

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.