Non-even roots on negative numbers result in -nan(ind)

The problem
Non-even roots on negative numbers break mathematics in Lua/Luau.
The equation (x) ^ (1/y), where x is any negative number, and y is any non-even number should always be equal to -(math.abs(x) ^ (1/y)). Instead, (x) ^ (1/y) returns -nan(ind).

From testing, this same bug happens in a range of other programming languages as well, including non-roblox lua and C.

Reproduction Steps
Simply in a script/console, type print((-1) ^ (1/3))

Expected Behavior
The result should always equal to -(math.abs(x) ^ (1/y))
Plotting the graph of x^(1/3) as proof that it should equal -1.

Actual Behavior
The result is -nan(ind) for any non-even root of a negative number.

Issue Area: Engine
Issue Type: Other
Impact: Moderate
Frequency: Constantly
Date First Experienced: 2021-12-06 00:12:00 (+00:00)
Date Last Experienced: 2021-12-06 00:12:00 (+00:00)


Any queries or quarrel please direct them to @jaschutte

3 Likes

It’s possibly because 1/3 is a floating point value once evaluated.

Lua(u) doesn’t know you intended for this to be a rational number, nor that you intended to implement the exact cubic root. (it is only a rational value in the program text) All it sees is the floating point value as the exponent, which is not a rational number. The underlying implementation it uses for the power operator likely just rejects non-integer powers on negative values for that reason.

ref: Re: compute cubic root with negative argument

Try plotting x^0.333334 or x^0.333332 (or even just x^0.33333, finite number of decimals) on your graph software to see the problem.

Roblox could provide a library function like math.root(n, r) or math.pow(n, p, q) to allow rational roots.

3 Likes

Can confirm this is intended. Thanks again for the report!