High-precision computing for Java and JS

Source: Internet
Author: User
Tags mul pow

Reprinted from: Http://blog.csdn.net/zhutulang/article/details/6844834#commentsJava:
Import Java.math.BigDecimal; /** * Because Java's simple type does not accurately operate on floating-point numbers, this tool class provides fine-grained floating-point arithmetic, including subtraction and rounding.      */public class arith{//default division operation precision private static final int def_div_scale = 10;      This class cannot instantiate private Arith () {}/** * to provide precise addition operations.          * @param v1 summand * @param v2 Addend * @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 ();      }/** * provides precise subtraction operations.          * @param v1 minuend * @param v2 * @return Two parameter 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 ();      }/** * provides accurate multiplication operations. * @param v1 by multiplier * @param v2 multiplier * @return two parameters of product */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 ();      }/** * provides (relative) accurate division operations, when there are no more than an endless case, accurate to * after the decimal point 10 digits, after the number rounded.          * @param v1 Dividend * @param v2 divisor * @return two parameters of quotient */public static double div (Double v1,double v2) {      Return Div (V1,v2,def_div_scale); }/** * provides (relative) accurate division operations.      When the exception occurs, the scale parameter refers to the fixed precision, and the subsequent numbers are rounded.      * @param v1 Dividend * @param v2 divisor * @param scale representation needs to be accurate to several decimal places.              * @return two parameters of quotient */public static double div (double v1,double v2,int scale) {if (scale<0) {          throw new IllegalArgumentException ("The scale must is a positive integer or zero");          } BigDecimal B1 = new BigDecimal (double.tostring (v1));          BigDecimal b2 = new BigDecimal (double.tostring (v2)); Return B1.Divide (b2,scale,bigdecimal.round_half_up). Doublevalue ();      }/** * Provides precise rounding of decimal digits. * @param v The number to be rounded * @param the scale after the decimal point retains several * @return rounded results */public static double round (double V , int scale) {if (scale<0) {throw new IllegalArgumentException ("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 ();   }  }
Js:
The Division function, which is used to obtain the exact division result//Description: The JavaScript division result will be error, when the two floating-point number is divided into more obvious.   This function returns a more accurate division result.   Call: Accdiv (ARG1,ARG2)//return value: Arg1 divided by the exact result of arg2 function Accdiv (arg1,arg2) {var t1=0,t2=0,r1,r2; Try{t1=arg1.tostring (). Split (".") [1].length}catch (e) {} try{t2=arg2.tostring (). Split (".") [1].length}catch (e) {} with (Math) {R1=number () (Arg1.tostring (). Replace (".", "")) R2=number (Arg2.tostring (). Replace ("."   , "")) return (R1/R2) *pow (10,T2-T1);   }}//Add a Div method to the number type, which is more convenient to call.   Number.prototype.div = function (ARG) {return Accdiv (this, ARG); }//multiplication function to get the exact multiplication result//description: The result of JavaScript multiplication will be error, it will be more obvious when two floating-point numbers multiply.   This function returns a more accurate multiplication result. Call: Accmul (ARG1,ARG2)//return value: Arg1 times the exact result of arg2 function Accmul (arg1,arg2) {var m=0,s1=arg1.tostring (), S2=arg2.tos   Tring (); Try{m+=s1.split (".") [1].length}catch (e) {} try{m+=s2.split (".") [1].length}catch (e) {} return Number (S1.replace (".", "")) *number (S2.replace (".", ""))/math.pow (10,M)}//   Adding a Mul method to the number type makes it more convenient to call. Number.prototype.mul = FunctiOn (ARG) {return Accmul (ARG, this); }//addition function for accurate addition//description: The addition of JavaScript will have an error, and it will be more obvious when the two floating-point numbers are added.   This function returns a more accurate addition result.   Call: Accadd (ARG1,ARG2)//return value: Arg1 plus arg2 's exact result function Accadd (arg1,arg2) {var r1,r2,m; Try{r1=arg1.tostring (). Split (".") [1].length}catch (e) {r1=0} try{r2=arg2.tostring (). Split (".")    [1].length}catch (e) {r2=0} m=math.pow (10,math.max (R1,R2)) return (arg1*m+arg2*m)/m}//Add an Add method to the number type, which is more convenient to call.   Number.prototype.add = function (ARG) {return accadd (arg,this);   }//include these functions where you want them, and then call it to calculate.        For example you want to calculate: 7*0.8, then change to (7). Mul (8)//Other operations similar, you can get more accurate results.       Subtraction functions function Subtr (ARG1,ARG2) {var r1,r2,m,n; Try{r1=arg1.tostring (). Split (".") [1].length}catch (e) {r1=0} try{r2=arg2.tostring (). Split (".")       [1].length}catch (e) {r2=0} m=math.pow (10,math.max (R1,R2));       Last modify by Deeka//dynamic control accuracy length n= (R1&GT;=R2)? R1:R2;  Return ((arg1*m-arg2*m)/m). ToFixed (n);   }

  

High-precision computing for Java and JS

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.