圆满一双至3位有效数字

有没有人知道如何将双倍数值转化为3个重要数字,如本网站上的示例

http://www.purplemath.com/modules/rounding2.htm

 double d = ...; BigDecimal bd = new BigDecimal(d); bd = bd.round(new MathContext(3)); double rounded = bd.doubleValue(); 
  public String toSignificantFiguresString(BigDecimal bd, int significantFigures ){ String test = String.format("%."+significantFigures+"G", bd); if (test.contains("E+")){ test = String.format(Locale.US, "%.0f", Double.valueOf(String.format("%."+significantFigures+"G", bd))); } return test; } 

如果你想手工完成:

 import java.lang.Math; public class SigDig { public static void main(String[] args) { System.out.println(" -123.456 rounded up to 2 sig figures is " + sigDigRounder(-123.456, 2, 1)); System.out.println(" -0.03394 rounded down to 3 sig figures is " + sigDigRounder(-0.03394, 3, -1)); System.out.println(" 474 rounded up to 2 sig figures is " + sigDigRounder(474, 2, 1)); System.out.println("3004001 rounded down to 4 sig figures is " + sigDigRounder(3004001, 4, -1)); } public static double sigDigRounder(double value, int nSigDig, int dir) { double intermediate = value/Math.pow(10,Math.floor(Math.log10(Math.abs(value)))-(nSigDig-1)); if(dir > 0) intermediate = Math.ceil(intermediate); else if (dir< 0) intermediate = Math.floor(intermediate); else intermediate = Math.round(intermediate); double result = intermediate * Math.pow(10,Math.floor(Math.log10(Math.abs(value)))-(nSigDig-1)); return(result); } } 

上述方法将double加倍到所需数量的有效数字,处理负数,并且可以明确地告知舍入或向下舍入

如何将双倍数值舍入为3位有效数字

你不能。 双打以二进制表示。 它们没有要舍入的小数位。 获得特定小数位数的唯一方法是将其转换为十进制基数并将其保留在那里。 将它转换回双倍的那一刻,你再次失去了小数精度。

对于所有风扇,无论在这里还是其他地方,转换为其他基数和返回,或乘以除以10的幂,请显示结果的双重值%0.001或任何所需的精度指示,并解释结果。

编辑:具体来说,这些技术的支持者需要解释以下代码的92%失败率:

 public class RoundingCounterExample { static float roundOff(float x, int position) { float a = x; double temp = Math.pow(10.0, position); a *= temp; a = Math.round(a); return (a / (float)temp); } public static void main(String[] args) { float a = roundOff(0.0009434f,3); System.out.println("a="+a+" (a % .0001)="+(a % 0.001)); int count = 0, errors = 0; for (double x = 0.0; x < 1; x += 0.0001) { count++; double d = x; int scale = 2; double factor = Math.pow(10, scale); d = Math.round(d * factor) / factor; if ((d % 0.01) != 0.0) { System.out.println(d + " " + (d % 0.01)); errors++; } } System.out.println(count + " trials " + errors + " errors"); } } 

我通常不会对数字本身进行舍入,而是在需要显示数字的时候对数字的字符串表示进行舍入,因为通常显示重要,需要舍入(尽管在情况下可能不是这样,也许是你的,但是如果是这样,你需要详细说明)。 这样,我的数字保持其准确性,但它的显示简化,更容易阅读。 为此,可以使用DecimalFormat对象,例如使用“0.000”字符串( new DecimalFormat("0.000")String.format("%.3f", myDouble) ,或使用String.format("%.3f", myDouble)或其他几种方式。

例如:

 // yeah, I know this is just Math.PI. double myDouble = 3.141592653589793; DecimalFormat myFormat = new DecimalFormat("0.000"); String myDoubleString = myFormat.format(myDouble); System.out.println("My number is: " + myDoubleString); // or you can use printf which works like String.format: System.out.printf("My number is: %.3f%n", myDouble);