简体   繁体   English

如何四舍五入到另一个数字的最接近的分数?

[英]How to round to nearest fraction of another number?

I want to add a special scaling mode where it snaps to the closest multiple. 我想添加一种特殊的缩放模式,使其捕捉到最接近的倍数。 Right now, scaling up is fine, it's linear and goes something like this: 现在,按比例放大是可以的,它是线性的,如下所示:

 // f(x := 35, n := 32) = 32
 // f(x := 66, n := 32) = 64
 x = floor(x / n) * n

But for scaling down, I want some sort of inverse exponential: 但是为了缩小比例,我想要某种反指数:

 // f(x := 18, n := 32) = 16
 // f(x := 12, n := 32) = 8
 // f(x := 7, n := 32) = 4

An implementation suggestion without using a loop in any language would suffice. 不使用任何语言的循环的实现建议就足够了。 My current implementation is as follows (which 100% works): 我当前的实现如下(100%有效):

float ScaleMultiple(float value, float multiple) {
    if (value > multiple) {
        return(floor(value / multiple) * multiple);
    } else if (value < multiple) {
        do {
            multiple /= 2.0f;
        } while (value >= multiple);
        return(multiple);
    } else {
        return(value);
    }
}

multiple is a positive floating point number and not necessarily a multiple of 2 and is at least equal to 1. value is a positive floating point number and is at least equal to 1. multiple是一个正浮点数,不一定是2的倍数,并且至少等于1。 value是一个正浮点数,并且至少等于1。

32 / 18 ~= 1.8 ~= 2, the result you want is 32 / 2, right? 32/18〜= 1.8〜= 2,您想要的结果是32/2,对吗? For the case of 12 and 32, this would yield 3 though, not four. 对于12和32,这将产生3,而不是4。 In order to get there, take the log-2 of that number, round that to an even number and then convert back. 为了到达那里,请以该数字的log-2为单位,将其四舍五入为偶数,然后再转换回去。 However, this has the problem that it doesn't work properly when n is not a power of two. 但是,这有一个问题,当n不是2的幂时,它不能正常工作。

You can get the correct results for the values you give in Java as follows: 对于Java中给出的值,您可以获得正确的结果,如下所示:

int f = (int)Math.pow(2,(int)(Math.log(x)/Math.log(2)));

There's insufficient information provided to answer the question for arbitrary n. 没有足够的信息来回答关于任意n的问题

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM