gpt4 book ai didi

algorithm - 如何找到给定范围内以大多数零十进制数字结尾的浮点值?

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:06:26 26 4
gpt4 key购买 nike

有没有人有算法可以找到“min”和“max”之间的浮点值,当以十进制打印时以最多零位结尾(或者具有最少的小数位,换句话说)。当然可能有几种方案:在500到2500之间,1000或者2000都可以。就我的目的而言,两者都可以。 这是为了在 sndfile-spectrogram 中重新实现轴标记代码,所以我的目标语言是 C,但数学/伪代码很好。

最佳答案

如果我正确理解你的问题,我认为这将获得最高的数字。

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.

关于algorithm - 如何找到给定范围内以大多数零十进制数字结尾的浮点值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35541146/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com