问题
From a given double
I want to get the next highest number according to some rules which, since I have some difficulty describing them, I will illustrate by examples:
Input Desired output
------- --------------
0.08 0.1
0.2 0.5
5 10
7 10
99 100
100 500
2345 5000
The output should be in some sense the 'next highest multiple of 5 or 10'.
I hope this is understandable; if not, let me know.
The implementation will be in java and input will be positive double
s.
回答1:
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 :-)
回答2:
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)
回答3:
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.
回答4:
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 onlypowers[n-1 .. n]
- or using logarithm approximation like cutting the exponent part out of the number and checking 4 elements of powers[].
来源:https://stackoverflow.com/questions/8244721/how-can-i-get-the-next-highest-multiple-of-5-or-10