How can i get the next highest multiple of 5 or 10

天大地大妈咪最大 提交于 2019-12-06 03:51:40
function top5_10 (x) {
  var ten = Math.pow(10, Math.ceiling(Math.ln(x)/Math.LN10)));
  if (ten > 10 * x) { ten = ten / 10; }
  else if (ten <= x) { ten = 10 * ten; }
  return x < ten / 2 ? ten / 2 : ten;
}

or something like this :-)

Here's a function that works on the sample data:

def f(x):
    lx = log10(x)
    e = floor(lx)
    if (lx - e) < log10(5):
        return 5 * 10 ** e
    else:
        return 10 ** (e+1)

Pseudo code should be something like this:

If number > 1
    n = 1
    While(true)
        If(number < n)
            return n
        If(number < n*5)
            return n*5
        n = n*10
Else
    n = 1.0
    While(true)
        If(number > n/2)
            return n
        If(number > n/10)
            return n*2
        n = n/10.0

For numbers > 1, it checks like this: if < 5, 5. if <10, 10, if < 50, 50. For numbers < 1, it checks like this: if > 0.5 1. if > 0.1, 0.5. etc.

If you intend to use doubles and need precise result, all methods using double-precision multiply/divide/log10 are not working (or at least are hard to implement and prove correctness). Multi-precision arithmetic might help here. Or use search like this:

powers = [1.e-309, 1.e-308, ..., 1.e309]
p = search_first_greater(powers, number)
if (number < p / 2.) return p / 2.
return p

search_first_greater may be implemented as:

  • linear search,
  • or binary search,
  • or direct calculation of the array index by n=round(log10(number)) and checking only powers[n-1 .. n]
  • or using logarithm approximation like cutting the exponent part out of the number and checking 4 elements of powers[].
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!