I need equation help

Currently, I’m faced with the daunting task of converting any number between 0 and 26, to a number between 0 and 1 (ideally with 26 being one). How would I do this?

1 Like

@tacovaIk

local function Equate(Number:number)
	if Number <= 26 and Number > 0 then
		return Number * 0.01 / 0.26		
	end
end
print(Equate(26))

if you have any questions then feel free to ask

3 Likes

Consider that 26/26 is 1 and 0/26 is 0.

This is called mapping a value from one range to another. E.g. if the value is 13, the “from” range is 0 to 26, and the “to” range is 0 to 1, the value mapped to the to range is 0.5. Here’s a function that maps a value from 1 range to another:

function map(v, lower1, upper1, lower2, upper2)
    local amount = (v - lower1) / (upper1 - lower1)
    return lower2 + amount * (upper2 - lower2)
end

You’d use it like so:

map(value, 0, 26, 0, 1)
2 Likes

thank you so much for your help

thank you, I really appreciate it :slight_smile:

These above solutions are stupidly complex for no reason. All you need to do is divide whichever number you are using by 26. 26/26 = 1, 13/26 = 0.5, 0/26 = 0.

5 Likes

Luis’s solution above may work, but it is not the best. Allow me to elaborate:

local function Equate(Number:number)
	if Number <= 26 and Number > 0 then -- if statement, two comparisons
		return Number * 0.01 / 0.26 -- return, multiplication & division
	end
end
print(Equate(26)) -- function call

In this function, 6 operations are performed. A function call, two comparisons, a return, a multiplication and a division. This is definitely not optimal if being called several times.
I should also mention that Tom_atoes’s method of division doesn’t work, as performing division often leads to backdoors in your game.

A better and faster solution to this problem would be using TNC(Table Number Conversion).

local conversionTable = {1/26, 2/26, 3/26, 4/26, 5/26, 6/26, 7/26, 8/26, 9/26, 10/26, 11/26, 12/26,13/26,14/26,15/26,16/26,17/26,18/26,19/26,20/26,21/26,22/26,23/26,24/26,25/26,26/26}
local myNumber = conversionTable[5] -- converts 5, which is between 0 and 26, to 5/26, which is between 0 and 1.
print(myNumber)

Now, you might say that this solution is actually slower, as it performs 26 division operations. My answer to you would be yes, it is slower at first but as you call it more and more, you start to see the benefits of TNC. Allow me to explain:

When using the first solution, you are running 5 operations PER CALL. When using TNC, you are running 26 when the script is first executed, but only 1 operation is ever executed per call, an index.
Edit: There isn’t even any call! Just goes to show how efficient this is.

I hope this solution helped, feel free to DM/reply if you have any issues.

2 Likes
if number == 26 then
    number = 1
else 
    if number == 1 then
        number = 0
end
2 Likes