有没有人有一个算法可以找到“min”和“max”之间的浮点值,以十进制打印时以最零位数结尾(或者具有最小的小数位,换句话说)。当然可能有几种解决方案:在500到2500的范围内,1000或2000都是好的。就我的目的而言,要么会这样做。 这是重新实现sndfile-spectrogram中的轴标记代码,所以我的目标语言是C,但是数学/伪代码很好。
答案 0 :(得分:0)
如果我理解你的问题,我认为这将得到最高的这个数字。
float max = 432.334, min = 431.214; // The numbers you are looking between
float r = 0.01; // The first decimal place to check
float x0 = max, x1 = max; // Working variables
while (x1 > min)
{
x0 = x1;
x1 = r*floor(x1/r)
r *= 10;
}
你的答案是x0。
编辑:更多解释
这可以通过将较大的数字向下舍入到连续增加的10的幂来进行。r*floor(x1/r)
将此向下舍入。作为一个有效的例子:
r = 0.001
min, max = 0.1212, 0.1315
x1 = max
# Store the old value
x0 = x1
= 0.1315
# Round down to the nearest r
x1 = r*floor(x1/r)
= 0.001*floor(0.1315/0.001)
= 0.001*floor(131.5)
= 0.001*131
= 0.131
# x1 is still larger than min, so multiply r by 10 and repeat
r = 10*r
= 10*0.001
= 0.01
x0 = x1
= 0.131
x1 = r*floor(x1/r)
= 0.01*floor(0.131/0.01)
= 0.01*floor(13.1)
= 0.01*13
= 0.13
# and again...
r = 10*r
= 10*0.01
= 0.1
x0 = x1
= 0.13
x1 = r*floor(x1/r)
= 0.1*floor(0.13/0.1)
= 0.1*floor(1.3)
= 0.1*1
= 0.1
# x1 is now smaller than min, so the loop ends. x0 is the last rounded value
# larger than min, so this is the answer.