到最近的好号码 [英] round to nearest nice number
问题描述
我正在编写一个应用程序,需要将标签舍入到最近的'nice'数字。我将在下面放一些代码来证明这一点,但我的问题是我使用了一系列其他ifs来找到这个数字,但我不能确定上限,所以这不是一个好的策略。是否有任何已知的算法或资源可以帮助我?
I'm writing an application which requires rounding labels to the nearest 'nice' number. I'll put some code below to demonstrate this, but my issue is that I was using a series of else ifs to find this number but I cannot be sure of the upper limit so this isn't really a good strategy. Are there any known algorithms or resources which could help me?
if (diff <= 1) {
roundAmount = 0.2;
} else if (diff <= 5) {
roundAmount = 1;
} else if (diff <= 10) {
roundAmount = 2;
} else if (diff <= 25) {
roundAmount = 5;
} else if (diff <= 50) {
roundAmount = 10;
} else if (diff <= 100) {
roundAmount = 20;
} else if (diff <= 250) {
roundAmount = 50;
} else if (diff <= 500) {
roundAmount = 100;
} else if (diff <= 1000){
roundAmount = 200;
} etc...
推荐答案
你可以在进行好数搜索之前,使用 Math.log10
来标准化所有值,如下所示:
You can use Math.log10
to normalize all values before doing your "nice number" search, something like this:
我刚刚意识到你使用的是Java而不是C#,所以我修改了一下代码。我没有编译器来测试它,但你应该得到一般的想法:
I just realized you are using Java instead of C#, so I modified the code a bit. I don't have a compiler around to test it, but you should get the general idea anyway:
static double getNicerNumber(double val)
{
// get the first larger power of 10
var nice = Math.pow(10, Math.ceiling(Math.log10(val)));
// scale the power to a "nice enough" value
if (val < 0.25 * nice)
nice = 0.25 * nice;
else if (val < 0.5 * nice)
nice = 0.5 * nice;
return nice;
}
// test program:
static void main(string[] args)
{
double[] values =
{
0.1, 0.2, 0.7,
1, 2, 9,
25, 58, 99,
158, 267, 832
};
for (var val : values)
System.out.printf("$%.2f --> $%.2f%n", val, getNicerNumber(val));
}
这将打印如下内容:
0,1 --> 0,1
0,2 --> 0,25
0,7 --> 1
1 --> 1
2 --> 2,5
9 --> 10
25 --> 50
58 --> 100
99 --> 100
158 --> 250
267 --> 500
832 --> 1000
这篇关于到最近的好号码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!