'Rounded number to a best suitable nearest number so that i can calculate the interval thats are factor of 2, 5 or 10
There can be any specified number, then I want to write a function to return the best upper limit number to calculate the interval.
To divide the number into 5 intervals, the best numbers are
- if less than or equal 5 = divide into 1, 2, 3, 4, 5
- if 10 => divide into 2, 4, 6, 8, 10
- if 25 => divide into 5, 10, 15, 20, 25
- if 50 => divide into 10, 20, 30, 40, 50
- if 100 => divide into 20, 40, 60, 80, 100
- if 125 => divide into 25, 50, 75, 100, 125
- If 500 => divide into 100, 200, 300, 400, 500
But the input number, cannot be that 5, 10, 25, 50, 100, 125, 500, ...
So I would like to write a function that can return the best bold number, but i am stuck now. I want to calculate on the fly. No predefined values as I don't know what would be the input number. For less than or equal to 10, i can add additional to handle, but greater than 10, I want to get through by some formula calculation.
| input | output |
|---|---|
| 8 | 10 |
| 13 | 25 |
| 110 | 125 |
| 456 | 500 |
| 1601 | 2000 |
| 53194 | 60000 |
Is there any formula to calculate so that I can write the function that takes the above input and return the output? Thanks a lot.
The reason not to split 110 into 22, 44, 66, 88, 110, these numbers are not suitable to appear in the chart axis except 2, 4, 6, 8 , 10.
Solution 1:[1]
I suggest defining your interval in some way like this:
You can then solve the resulting inequalities by taking logarithms, and take the minimum viable solution to find the interval.
function interval(n, steps=5) {
// Find the minimum x such that x = a*b^k >= n / steps, where k is an integer
const solve = (a, b) => a * b ** Math.ceil(Math.log((n / steps) / a) / Math.log(b));
// Return the lowest of the possible solutions
return Math.min(
solve(1, 10),
solve(2, 10),
solve(5, 10),
solve(25, 10)
);
}
// alternatively const interval = (n, steps=5) => Math.min(...[1, 2, 5, 25].map(a => a * 10 ** Math.ceil(Math.log10((n / steps) / a))));
const inputs = [5, 8, 13, 110, 456, 1601, 53194];
console.log("input\t int\t limit");
for (const n of inputs) {
console.log(n, '\t', interval(n), '\t', 5 * interval(n));
}
This does not match your suggested output in all cases, but does provide sensible and consistent values. You could adjust the forms that are allowed if you want to tweak this.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
