首页 > 解决方案 > 四舍五入到给定值的最接近倍数

问题描述

如果我们有一个任意doublef、另一个值v和一个乘法因子p,我怎样才能将该值捕捉f到最接近的vp

例子:

乘法会像这样

...

f最接近3200.0所以函数应该返回3200.0

实际上有一个名字,我似乎忘记了,也许这就是我找不到这样一个功能的原因。

标签: cmath

解决方案


Let k = floor(log_p(f/v)) where log_p(x) = log(x)/log(p) is the logarithm to base p function. It follows from the properties of floor and log that p^k v <= f < p^(k+1) v, which gives the two closest values to f of the form p^n v.

Which of those two values to choose depends on the exact definition of "nearest" in your use-case. If taken in the multiplicative sense (as would be natural on a log scale), that "nearest" value can be calculated directly as p^n v where n = round(log_p(f/v)) = round(log(f/v)/log(p)).


推荐阅读