Reputation: 2488
If we have an arbitrary double
value f
, another one v
and a multiplication factor p
, how can I snap the value f
to the nearest v
power of p
?
Example:
the multiplications will go like this
v
)p
)...
f
is closest to 3200.0
so the function should return 3200.0
There was actually a name for this, which I seem to have forgotten and maybe this is why I couldn't find such a function.
Upvotes: 2
Views: 67
Reputation: 17648
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))
.
Upvotes: 2