So I used my remaining brain cells to make this function that rounds numbers for a module, It works but has a high delay because of the for loop, And i don’t know if there is any faster way than this I need help pls
Note: It works because while I was doing for loops, I realized that the goal gets rounded by the index, Then created this thingy
Code
local function Abs(Number: number): number
if Number > 0 then
return Number
else
return -Number
end
end
local function Round(Number : number): number
local NearestNumber, LastNumber = Number, 0
for Index=1, Number + 2, if Number > 0 then 1 else -1 do
local NumDustance = Abs(Number - Index)
if NumDustance < NearestNumber then
LastNumber = Index
NearestNumber = NumDustance
end
continue
end
return LastNumber
end
print(Round(10.5)) -- 10
print(Round(2147483645)) -- YourPCWillCrashlol
Why are you writing the rounding function in Lua when C/C++ one provided by math library works fine.
I am someone who has worked closely with Lua VM, so I can say this with some authority.
C/C++ code is always faster than extremely optimized Lua Code, so you should always go with the built in functions because:
Well Tested
Natively executes (close to hardware) so it’s fast.
Luau inlines library calls, so it’s almost equivalent of calling just one instruction.
Whatever your use case is, if you are wanting to make a custom one in Lua, I have a O(1) solution for you.
Because Luau uses double precision IEC-559 (aka IEEE-754) floats, as most do, and assuming your numbers are relatively small (the method is guaranteed to work for inputs between -251 and 251), the following efficient code will perform rounding, which is usually round to nearest, ties to even:
local function round(num)
return num + (2^52 + 2^51) - (2^52 + 2^51)
end
But for larger numbers, you can go with another (less efficient, of course) algorithm that performs the same rounding but works for all numbers:
local function round(num)
local ofs = 2^52
if math.abs(num) > ofs then
return num
end
return num < 0 and num - ofs + ofs or num + ofs - ofs
end