四舍五入至显著位任意数目 [英] rounding to an arbitrary number of significant digits
问题描述
你怎么能轮的任意的数量(不只是整数> 0)到N显著的数字?
How can you round any number (not just integers > 0) to N significant digits?
例如,如果我要舍入到3显著的数字,我在寻找一个公式,可以采取:
For example, if I want to round to 3 significant digits, I'm looking for a formula that could take:
1239451,返回1,240,000
1,239,451 and return 1,240,000
12.1257并返回12.1
12.1257 and return 12.1
0.0681,并回到0.0681
.0681 and return .0681
5,并返回5
自然算法不应该是硬codeD只能处理3 N,尽管这将是一个开始。
Naturally the algorithm should not be hard-coded to only handle N of 3, although that would be a start.
推荐答案
下面是同样的code在Java中没有12.100000000000001错误其他答案有
Here's the same code in Java without the 12.100000000000001 bug other answers have
我也删除重复code,改变了动力
来一个整数类型,以prevent浮动的问题时, N - ð
完成,并取得了很长的中间更加清晰
I also removed repeated code, changed power
to a type integer to prevent floating issues when n - d
is done, and made the long intermediate more clear
的缺陷已通过用小数目乘以造成大量。相反,我把同样大小的两个数字。
The bug was caused by multiplying a large number with a small number. Instead I divide two numbers of similar size.
修改
修正了更多的错误。加入检查0,因为这将导致为NaN。所取得的实际功能与负数(原code不处理负数,因为日志的负数是复数)
EDIT
Fixed more bugs. Added check for 0 as it would result in NaN. Made the function actually work with negative numbers (The original code doesn't handle negative numbers because a log of a negative number is a complex number)
public static double roundToSignificantFigures(double num, int n) {
if(num == 0) {
return 0;
}
final double d = Math.ceil(Math.log10(num < 0 ? -num: num));
final int power = n - (int) d;
final double magnitude = Math.pow(10, power);
final long shifted = Math.round(num*magnitude);
return shifted/magnitude;
}
这篇关于四舍五入至显著位任意数目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!