可以有任意指定的數字,那么我想寫一個函式來回傳最佳的上限數字來計算區間。
要將數字分成 5 個區間,最好的數字是
- 如果小于或等于5 = 分為 1、2、3、4、5
- 如果10 => 分為 2、4、6、8、10
- 如果25 => 分為 5、10、15、20、25
- 如果50 => 分為 10、20、30、40、50
- 如果100 => 分為 20、40、60、80、100
- 如果125 => 分為 25、50、75、100、125
- 如果500 => 分為 100、200、300、400、500
但是輸入的數字,不能是 5, 10, 25, 50, 100, 125, 500, ...
所以我想寫一個可以回傳最佳粗體數字的函式,但我現在卡住了。我想即時計算。沒有預定義的值,因為我不知道輸入數字是什么。對于小于等于10,我可以添加額外的處理,但大于10,我想通過一些公式計算來解決。
| 輸入 | 輸出 |
|---|---|
| 8 | 10 |
| 13 | 25 |
| 110 | 125 |
| 456 | 500 |
| 1601 | 2000 |
| 53194 | 60000 |
是否有任何公式可以計算,以便我可以撰寫接受上述輸入并回傳輸出的函式?非常感謝。
不將 110 拆分為 22、44、66、88、110 的原因,這些數字不適合出現在圖表軸上,除了 2、4、6、8、10。
uj5u.com熱心網友回復:
我建議以如下方式定義您的間隔:
然后,您可以通過取對數來解決由此產生的不等式,并采用最小可行解來找到區間。
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));
}
這并非在所有情況下都符合您建議的輸出,但確實提供了合理且一致的值。如果您想調整它,您可以調整允許的表格。
uj5u.com熱心網友回復:
您可以創建一個限制值陣列,并find在增量變為正數時使用 to 獲取第一個數字
const limits = [10, 25, 125, 500, 2000]
const findLimit = (limits, n) => limits .find(a => a - n >= 0)
const inputs = [8, 13, 110, 456, 1601]
inputs.forEach(n =>
console.log(n, findLimit(limits, n))
)
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/477028.html
標籤:javascript 算法 数学
下一篇:填充線性模型中的缺失資料
