四舍五入 - 成为一条规则

时间:2012-05-03 13:55:29

标签: math language-agnostic rounding

我需要将一个数字舍入1/32,然后将其舍入1/100。我需要将其转换为一个单一的舍入规则(使用古老的程序......)。我可以将原始数字乘以并除以所有这些,只是不能再绕两次....

有没有办法以数学方式做到这一点?

谢谢!

kcross

1 个答案:

答案 0 :(得分:2)

如果你使用的任何东西都允许你定义函数,那么最可读的实现就是:

function round(x, interval){
    //implementation left as an exercise to the reader
}

#rounds x by interval1, then by interval2
function doubleRound(x, interval1, interval2){
    return round(round(x, interval1), interval2)
}

但是如果你只有简单算术,你可以将所有内容展开到一个语句中。

要将非负数x舍入到最近的N间隔,可以使用以下公式:

round(x,N) = floor((x + (N/2)) / N) * N

要四舍五入,你将函数嵌入其中:

round(round(x, N1), N2) = floor(((floor((x + (N1/2)) / N1) * N1) + (N2/2)) / N2) * N2

因此,要使用1/32然后1/100,请使用:

floor(((floor((x + ((1/32)/2)) / (1/32)) * (1/32)) + ((1/100)/2)) / (1/100)) * (1/100)