c - 四舍五入到给定值的最接近倍数
问题描述
如果我们有一个任意double
值f
、另一个值v
和一个乘法因子p
,我怎样才能将该值捕捉f
到最接近的v
幂p
?
例子:
- f = 3150.0
- v = 100.0
- p = 2
乘法会像这样
- 100 (
v
) - 200(乘以
p
) - 400
- 800
- 1600
- 3200
...
f
最接近3200.0
所以函数应该返回3200.0
实际上有一个名字,我似乎忘记了,也许这就是我找不到这样一个功能的原因。
解决方案
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))
.
推荐阅读
- php - 为什么我的本地主机显示我的 php 脚本?
- python - Numpy 加载显示所有零的文件
- firebase - Dialogflow 使用 Firebase 连接到 MQTT 代理?
- python - 为什么不能导入子模块?
- c# - 切换到默认大小写
- python - 在 python 中增加 bd_address 是否有更短的方法?
- c++ - 使用 ++ 运算符会导致意外结果
- javascript - 使用导入将单个文件显示模块模式 javascript 转换为多文件
- reactjs - 如何去抖动一个函数,在 React 中使用 onChange 时会立即调用另一个函数?
- jquery - jQuery 多个 If