四舍五入到任意有效位数

您如何将任何数字(不仅是整数> 0)舍入为N个有效数字?


例如,如果我想四舍五入到三位有效数字,我正在寻找一个可能采用的公式:


1,239,451,回报1,240,000


12.1257并返回12.1


.0681并返回.0681


5并返回5


自然,不应将算法硬编码为仅处理3的N,尽管这只是一个开始。


白猪掌柜的
浏览 624回答 3
3回答

红糖糍粑

这是Java中的相同代码,没有12.100000000000001错误,其他答案也有我还删除了重复的代码,更改power为整数类型以防止n - d完成操作时出现浮动问题,并使长中间体更加清晰该错误是由大量乘以少量引起的。相反,我将两个相似大小的数字相除。编辑修正了更多的错误。添加了对0的检查,因为这会导致NaN。使函数实际使用负数(原始代码不处理负数,因为负数的对数是复数)public static double roundToSignificantFigures(double num, int n) {&nbsp; &nbsp; if(num == 0) {&nbsp; &nbsp; &nbsp; &nbsp; return 0;&nbsp; &nbsp; }&nbsp; &nbsp; final double d = Math.ceil(Math.log10(num < 0 ? -num: num));&nbsp; &nbsp; final int power = n - (int) d;&nbsp; &nbsp; final double magnitude = Math.pow(10, power);&nbsp; &nbsp; final long shifted = Math.round(num*magnitude);&nbsp; &nbsp; return shifted/magnitude;}

守着星空守着你

这是一个简短而有趣的JavaScript实现:function sigFigs(n, sig) {&nbsp; &nbsp; var mult = Math.pow(10, sig - Math.floor(Math.log(n) / Math.LN10) - 1);&nbsp; &nbsp; return Math.round(n * mult) / mult;}alert(sigFigs(1234567, 3)); // Gives 1230000alert(sigFigs(0.06805, 3)); // Gives 0.0681alert(sigFigs(5, 3)); // Gives 5

胡子哥哥

摘要:double roundit(double num, double N){&nbsp; &nbsp; double d = log10(num);&nbsp; &nbsp; double power;&nbsp; &nbsp; if (num > 0)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; d = ceil(d);&nbsp; &nbsp; &nbsp; &nbsp; power = -(d-N);&nbsp; &nbsp; }&nbsp; &nbsp; else&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; d = floor(d);&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; power = -(d-N);&nbsp; &nbsp; }&nbsp; &nbsp; return (int)(num * pow(10.0, power) + 0.5) * pow(10.0, -power);}因此,您需要找到第一个非零数字的小数位,然后保存下N-1个数字,然后根据其余数字舍入第N个数字。我们可以使用日志来做第一个。log 1239451 = 6.09log 12.1257 = 1.08log 0.0681&nbsp; = -1.16因此,对于大于0的数字,请取对数的上限。对于数字<0,请使用日志的底数。现在我们有数字d:第一种情况为7,第二种情况为2,第三种情况为-2。我们必须将(d-N)数字四舍五入。就像是:double roundedrest = num * pow(10, -(d-N));pow(1239451, -4) = 123.9451pow(12.1257, 1)&nbsp; = 121.257pow(0.0681, 4)&nbsp; &nbsp;= 681然后执行标准的舍入操作:roundedrest = (int)(roundedrest + 0.5);并撤消战俘。roundednum = pow(roundedrest, -(power))功率是上面计算出的功率。关于准确性:Pyrolistical的答案确实更接近实际结果。但是请注意,无论如何您都不能完全代表12.1。如果按以下方式打印答案:System.out.println(new BigDecimal(n));答案是:Pyro's: 12.0999999999999996447286321199499070644378662109375Mine: 12.10000000000000142108547152020037174224853515625Printing 12.1 directly: 12.0999999999999996447286321199499070644378662109375因此,请使用Pyro的答案!
打开App,查看更多内容
随时随地看视频慕课网APP