Java high-precision arithmetic operation (unlimited)

Source: Internet
Author: User

Java high-precision arithmetic operation (unlimited)

Package cn. skyatom. common; import java. math. bigDecimal; import java. util. regex. matcher; import java. util. regex. pattern;/*** basic Arithmetic operation ** @ author ZWK */public class Arithmetic {private static String getUUID () {return java. util. UUID. randomUUID (). toString (). replaceAll ("-", "");} public static void main (String [] args) throws Exception {java. util. map <String, BigDecimal> values = new java. util. hashMap <String, BigDecimal> (); BigDecimal AAF = new BigDecimal (5.5); BigDecimal BCCC = new BigDecimal (8); BigDecimal QQC = new BigDecimal (-8.33 ); bigDecimal DCC = new BigDecimal (2); BigDecimal EE = new BigDecimal (23); BigDecimal BF = new BigDecimal (2.5); BigDecimal A1 = new BigDecimal (12 ); bigDecimal A2 = new BigDecimal (4); BigDecimal A3 = new BigDecimal (5); BigDecimal A4 = new BigDecimal (15); values. put ("AAF", AAF); values. put ("BCCC", BCCC); values. put ("QQC", QQC); values. put ("DCC", DCC); values. put ("EE", EE); values. put ("BF", BF); values. put ("A1", A1); values. put ("A2", A2); values. put ("A3", A3); values. put ("A4", A4); // values. put ("B1", 4F); // values. put ("B2", 15f); // values. put ("B3", 55f); // values. put ("B4", 2f); // values. put ("B5", 5f); String str = "AAF * BCCC + QQC/DCC-EE * BF + (A1*(A2/(A3 + A4) "; // 5.5*8 + (-8.33)/2-23*2.5 + (12*(4/(5 + 15 ))) // String str = "B1 * B2 + B3-B4/B5"; // empty/// BigDecimal v = getArithmeticValue (str, values); System. out. println ("Result:" + getArithmeticFloatValue (str, values);}/*** run the operation to obtain the expression result. Float value ** @ param str * @ param values * @ return * @ throws Exception */public static float getArithmeticFloatValue (String str, java. util. map <String, BigDecimal> values) throws Exception {return getArithmeticValue (str, values ). floatValue ();} public static int getArithmeticIntValue (String str, java. util. map <String, BigDecimal> values) throws Exception {return getArithmeticValue (str, values ). intVal Ue ();} public static long getArithmeticLongValue (String str, java. util. map <String, BigDecimal> values) throws Exception {return getArithmeticValue (str, values ). longValue ();}/*** replace brackets ** @ param str * @ param values * @ return when all replications are complete, null, returns the replaced String */private static String replaceBrackets (String str, java. util. map <String, BigDecimal> values) {String v = ""; String tmp = null; // temporary String value Pattern Patt = Pattern. compile ("\ ([A-Za-z0-9 \. \ * \ + \-/] *?) \) ", Pattern. DOTALL); Matcher mat = patt. matcher (str); if (mat. find () {tmp = mat. group (1);} if (tmp! = Null) {String uuid = getUUID (); BigDecimal value = getBasicArithmeticValue (tmp, values); str = str. replace ("(" + tmp + ")", uuid); values. put (uuid, value); v = str; v = replaceBrackets (v, values);} else {v = str;} return v, obtain the expression result ** @ param str expression string * @ param values value storage table * @ return returns the operation value * @ throws java. lang. an Exception */public static BigDecimal getArithmeticValue (String str, java. util. map <String, BigDecimal> values) throws Exception {str = str. replaceAll ("\ s *", ""); // empty String s = replaceBrackets (str, values); if (s! = Null |! S. trim (). equals ("") {str = s;} return getBasicArithmeticValue (str, values );} /*** basic arithmetic operation ** @ param str basic arithmetic operation * @ param values value storage table * @ return */private static BigDecimal getBasicArithmeticValue (String str, java. util. map <String, BigDecimal> values) {str = multiReg (str, values); str = divReg (str, values); java. util. list <Boolean> signs = getplusperformancesign (str); // obtain the java symbol. util. list <String> valuesign = getValueSign (str); // Replace the BigDecimal v = getValue (valuesign, signs, values); return v ;} /***** obtain the result ** @ param valuesign Value Replacement symbol * @ param signs symbol * @ param values value storage table * @ return */private static BigDecimal getValue (java. util. list <String> valuesign, java. util. list <Boolean> signs, java. util. map <String, BigDecimal> values) {BigDecimal value = values. get (valuesign. get (0); for (int I = 0; I <signs. size (); I ++) {if (signs. get (I) {value = value. add (values. get (valuesign. get (I + 1); // value + = values. get (valuesign. get (I + 1);} else {value = value. subtract (values. get (valuesign. get (I + 1); // value-= values. get (valuesign. get (I + 1) ;}} return value ;} /*** get the replacement symbol ** @ param str the string to be matched * @ return returns the replacement value symbol */private static java. util. list <String> getValueSign (String str) {java. util. list <String> list = new java. util. arrayList <String> (); Pattern patt = Pattern. compile ("[a-zA-Z0-9] * {1})", Pattern. DOTALL); Matcher mat = patt. matcher (str); while (mat. find () {if (mat. group (1 ). trim (). equals ("") {continue;} list. add (mat. group (1);} return list;}/*** get addition and subtraction symbol ** @ param str string to be matched * @ return returns the signed order. the plus sign is true, the minus sign is false */private static java. util. list <Boolean> getPlusReduceSign (String str) {java. util. list <Boolean> list = new java. util. arrayList <Boolean> (); Pattern patt = Pattern. compile ("([a-zA-Z0-9] * {1} ([+ |-]) [a-zA-Z0-9] * {1})", Pattern. DOTALL); Matcher mat = patt. matcher (str); while (mat. find () {if (mat. group (2 ). trim (). equals ("+") {list. add (true);} else {list. add (false) ;}} return list ;} /*** multiplication regular ** @ param str operator expression String * @ param values value storage table * @ return returns the reconstructed String */private static String multiReg (String str, java. util. map <String, BigDecimal> values) {Pattern patt = Pattern. compile ("([a-zA-Z0-9] * {1} \ * [a-zA-Z0-9] * {1})", Pattern. DOTALL); Matcher mat = patt. matcher (str); while (mat. find () {str = excMultiplication (str, mat. group (1), values);} return str ;} /*** Division Regular ** @ param str operator expression String * @ param values value storage table * @ return returns the reconstructed String */private static String divReg (String str, java. util. map <String, BigDecimal> values) {Pattern patt = Pattern. compile ("([a-zA-Z0-9] * {1} \/[a-zA-Z0-9] * {1})", Pattern. DOTALL); Matcher mat = patt. matcher (str); while (mat. find () {str = excDivsion (str, mat. group (1), values);} return str ;} /*** calculate multiplication ** @ param str all operation strings * @ param value calculate the multiplication string * @ param map value storage table * @ return returns the reconstructed string */ private static String excMultiplication (String str, string value, java. util. map <String, BigDecimal> map) {String vs [] = value. split ("\ *"); BigDecimal v1 = map. get (vs [0]); BigDecimal v2 = map. get (vs [1]); BigDecimal x = v1.multiply (v2); map. remove (vs [0]); map. remove (vs [1]); String uuid = getUUID (); map. put (uuid, x); str = str. replace (value, uuid); return str ;} /*** calculation start ** @ param str all operation strings * @ param value calculation multiplication string * @ param map value storage table * @ return returns the reconstructed string */ private static String excDivsion (String str, string value, java. util. map <String, BigDecimal> map) {String vs [] = value. split ("\/"); BigDecimal v1 = map. get (vs [0]); BigDecimal v2 = map. get (vs [1]); BigDecimal x = v1.divide (v2); map. remove (vs [0]); map. remove (vs [1]); String uuid = getUUID (); map. put (uuid, x); str = str. replace (value, uuid); return str ;}}
Recently, when developing a company's performance system, the boss is very stingy and doesn't want to buy a performance system on the market .. As a result, I started programming again ...... Reports are involved in the system, and the performance among employees and the algorithm for real-time salary are updated at intervals. Therefore, it is impossible to compile the algorithm into the source code, and the report formula is required for calculation (of course, the report formula system needs to be developed separately, which is not described here ). The above is the JAVA code. The idea is to treat the parameters in the formula as strings rather than purely numbers. During each operation, only binary operations are performed. After the operation, the data is saved and the data in the original data table is deleted. In this loop, you do not need to consider the limitations of parentheses. When implementing the Code, the float or double type is taken into account. However, when the final result is displayed, both types of precision will be lost. Therefore, the BigDecimal type is used, it can also be considered for long-term operation. There are many areas to be optimized. If you are interested, you can leave a message to contact us ......

Related Article

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.