I am currently trying to convert larger numbers to a 1-7 number range. For example, let’s say I have the number range 8-14 and my number is 9, how would I convert it to the number 2?
Cant you just subtract it by 7?
If the number range is larger like 15-21, it wouldn’t work
Im thinking something like this should work if you have the range and the number that goes into the range
local range = NumberRange.new(8, 14)
x = 9 -- number your trying to scale down
local answer = (x + 1) - range.Min
print(answer) -- 2
same thing works with 15-21
local range = NumberRange.new(15, 21)
x = 16 -- number your trying to scale down
local answer = (x + 1) - range.Min
print(answer) -- 2
and then if you want to make sure its between 1-7 you could easily add a check to it
the only problem is, is that I wouldn’t be able to know what number that range is in, because the range keeps going on by increments of 7
if you have the number but not the range you can get the range with something like this
--get the range
local x = 9 -- number your scaling down
local increment = 7
local rangeMin = math.floor((x - 1) / increment) * increment + 1 -- get the rangemin
local rangeMax = rangeMin + increment - 1 -- get the rangemax
-- scale it down
local range = NumberRange.new(rangeMin,rangeMax)
local answer = (x + 1) - range.Min
print(answer) -- 2
Can’t remember a way I’d exactly do it… but assuming you’d want to clamp values in the range of 1-7(including 0):
local Range = 7
local function SnapToRange(Num: number)
local SnappedNum = math.floor(Num%Range) --Modulus
return SnappedNum > 0 and SnappedNum or Range --Previously had it hardcoded as 7...
end
print(SnapToRange(44.562))
The modulus operation will return 0 for numbers divisible by our range 7.
Try linear interpolation? First calculate the alpha given the ranges and the value, and then reverse that operation and find the value given alpha and the range
value = from + (to - from)*alpha
alpha = (value - from) / (to - from)
local function toAlpha(v: number, f: number, t: number): number
return (v-f)/(t-f)
end
local function toValue(a: number, f: number, t: number): number
return f + a*(t-f)
end
print(toValue(toAlpha(9, 8, 14), 1, 7)) --> 2
--break it down:
local alpha = toAlpha(9, 8, 14) --find the alpha of the value 9 in the range [8, 14]
print(alpha) --> 0.16666666...
print(toValue(alpha, 1, 7)) --using the alpha, find the value in the range [1, 7]
This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.