Rounding to the nearest multiple of a given value

Viewed 45

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:

  • f = 3150.0
  • v = 100.0
  • p = 2

the multiplications will go like this

  • 100 (v)
  • 200 (multiplied by p)
  • 400
  • 800
  • 1600
  • 3200

...

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.

1 Answers

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)).

Related