[英]How can i get the next highest multiple of 5 or 10
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: 从给定的
double
我要根据一定的规则这,因为我有一个描述他们一些困难,我会通过例子说明,以获得下一个最高数:
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'. 在某种意义上,输出应该是“5或10的下一个最高倍数”。
I hope this is understandable; 我希望这是可以理解的; if not, let me know.
如果没有,请告诉我。
The implementation will be in java and input will be positive double
s. 执行将在java中输入将是正
double
s。
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. 对于数字> 1,它检查如下:if <5,5。if <10,10,if <50,50。对于数字<1,它检查如下: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). 如果您打算使用双精度并且需要精确的结果,那么使用双精度乘法/除法/ log10的所有方法都不起作用(或者至少很难实现并证明是正确的)。 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: search_first_greater可以实现为:
n=round(log10(number))
and checking only powers[n-1 .. n]
n=round(log10(number))
直接计算数组索引并仅检查powers[n-1 .. n]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.