Magnitude with numbers? or how to get the closest number from 2 numbers

for example:
the num is 150
the num points is 200 and 300
how do i get the closest from that?

math.abs(a - b) will return the absolute difference between the 2 numbers, a could be 150, and b could be 200 or 300, you’d just need to find the smallest difference between whatever a is and each of the numbers

image

local nums = {250,300,350}

for _,v in nums do
if math.abs(150-v) then
print(v)
end
end

i don’t really understand what is going on

1 Like

Yes you are only checking if math.abs(150 - v) is truthy, which it always will be. You need to compare each of the numbers to find what number has the smallest absolute difference.

Here’s an example of how to create an algorithm that does roughly this (albeit lacking the math.abs but implementing that is easy enough, it’s the first example):

1 Like

image

local nums = {300,133,350}

local t = {}
local min = math.huge
for _,v in nums do
if math.abs(150-v) then
table.insert(t,v)
end
end
print(t)
for i,v in ipairs(t) do
min = math.min(min, v)
end
print(min)

1 Like
local nums = { 300, 133, 350 }

local smallestDifference, smallestNumber = math.huge, math.huge

for _, num in nums do 
    local diff = math.abs(150 - num)

    if diff < smallestDifference then
        smallestDifference, smallestNumber = diff, num
    end
end
1 Like

i solved problem.

local nums = {300,133,350}

local t = {}
local min = math.huge
for _,v in nums do
if v >= 150 then
table.insert(t,v)
end
end
for i,v in ipairs(t) do
min = math.min(min, v)
end
print(min)

i made this.
math.abs is not the thing i want, also i’m sorry for not providing much details because it’s about to turn 3 am and i’m really tired.

1 Like

no, that’s not the thing i want

1 Like

yeah i realized haha
i reread your initial post and realized what you wanted

2 Likes

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