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

From the given double I want to get the next largest number in accordance with some rules, which, since I have difficulties with their description, I will illustrate with examples:

 Input Desired output ------- -------------- 0.08 0.1 0.2 0.5 5 10 7 10 99 100 100 500 2345 5000 

The result should be, in a sense, "the next highest multiple of 5 or 10".

I hope this is clear. if not, let me know.

The implementation will be in java and the input will be positive double s.

+3
source share
4 answers
 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 :-)

+4
source

Here is the function that works with 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) 
+2
source

The pseudocode should look 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, he checks the following: if <5, 5. if <10, 10, if <50, 50. For numbers <1, he checks the following: if> 0.5 1. if> 0.1, 0, 5. and etc.

+2
source

If you intend to use doubling and need the exact result, all methods using double-precision multiply / divide / log10 do not work (or at least it is difficult to implement and prove the correctness). Multipoint arithmetic can help here. Or use the search as follows:

 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 can be implemented as:

  • linear search
  • or binary search,
  • or direct calculation of the array index on n=round(log10(number)) and checking only powers[n-1 .. n]
  • or using the logarithm approximation, for example, cutting the exponent from a number and checking 4 authorization elements [].
0
source

All Articles