Java's simple type for accurate floating point calculation

xiaoxiao2021-03-06  54

Since Java's simple type is not able to calculate the floating point number, this tool class provides accurate floating point calculations, including addition and subtraction and division and rounding.

Import java.math.bigdecimal;

Public class arith {// default division operation accuracy private static final int def_div_scale = 10;

// This class cannot instantiate private arch () {}

/ ** * Provide an accurate addition operation. * @Param V1 Plus * @Param V2 plus * @return two parameters and * / public static double add (double v1, double v2) {BigDecimal B1 = New BigDecimal (Double.toString (V1)); BigDecimal B2 = New BigDecimal (Double.Tostring (V2)); Return B1.Add (b2) .doubleValue ();

/ ** * Provide an accurate subtraction operation. * @Param V1 is reduced * @Param V2 reduction * @return two parameters of difference * / public static double sub (double v1, double v2) {BigDecimal B1 = New BigDecimal (Double.toString (V1)); BigDecimal B2 = New BigDecimal (Double.ToString (V2)); Return B1.Subtract (b2) .doublevalue ();

/ ** * Provide precise multiplication. * @Param V1 Multiply * @Param V2 Multiply * @return Two Parameters * / Public Static Double Mul (Double V1, Double V2) {BigDecimal B1 = New BigDecimal (Double.toString (V1)); BigDecimal B2 = New BigDecimal (Double.Tostring (V2)); Return B1.Multiply (b2) .doublevalue ();

/ ** * Provide (relatively) accurate division operation * @Param V1 Demand * @Param V2 divisor * @Return two parameters * / public static double div (double V1, double v2) {Return Div (V1, V2, DEF_DIV_SCALE);}

/ ** * Provides (relatively) precise division operations. When an endless case occurs, the Scale parameter refers to * fixed precision, and the number will be rounded. * @Param V1 is divisted * @Param V2 divisor * @Param scale means that several digits are required to be accurate to the decimal point. * @return two parameters * / public static double div (Double V1, Double V2, int Scale) {if (scale <0) {throw new illegalgumentException ("The Scale Must Be a Positive Integer OR Zero);} BigDecimal B1 = New BigDecimal (V1)); BigDecimal B2 = New BigDecimal (Double.Tostring (V2)); Return B1.DIVIDE (B2, Scale, BigDecimal.Round_Half_up) .doubleValue ();} / ** * Provide precise decimal rounds. * @Param V Requesquees a number of numbers * @Param Scale reserved several * @return four-year-old result * / public static double round (double v, int scale) {if (scale <0) {throw new IllegaArGumentexception (" The scale must be a positive integer or zero ");} BigDecimal b = new BigDecimal (Double.toString (v)); BigDecimal one = new BigDecimal (" 1 "); return b.divide (one, scale, BigDecimal.ROUND_HALF_UP .doublevalue ();}}

转载请注明原文地址:https://www.9cbs.com/read-115133.html

New Post(0)