Java type and maintenance accuracy during high precision digital operations

xiaoxiao2021-04-10  413

Types

1.1. About the reference

The Java language first assumes that we only want to perform object-oriented programming, that is to say, you must first transfer your ideas into a pure object-oriented world before using it. Everything in Java is in an object. A Java program is also an object itself.

Anything can be seen as an object, but pay attention to although everything will be regarded as an object, the identifier of the operation is actually a reference to an object (Reference). Just because there is a reference that doesn't mean that there must be an object to connect to it, if you want to accommodate a word or sentence, you can create a string reference:

String S;

But here is only the reference is not an object. If you send a message to S, you will get a runtime error, which is because s does not connect to anything; therefore a more secure approach is to create a reference I remember that initialization is performed anyway:

String s = "ASDF";

When you create a reference, we hope that it is connected to the same new object, usually with the New keyword to achieve this. The meaning of New is an object that turns me into this type, so the example above can also be reached:

String s = new string ("ASDF");

1.2. Java type

There are several concepts in the Java language: class (ie, our own type of type), basic type (system originally included), object, reference

We use the Class ID in Java that is called class, from class production objects, objects belong to class; objects are specified by their classes, and the basic type is declared and initialized by procedures. The basic types have corresponding packages, and there is a corresponding method in the package, thereby achieving the transformation of basic types to class objects;

For objects, by reference to operation objects, reference is not object itself; for basic types, reference is both type value itself;

1.2.1. Basic type

There is a series of types in Java to take us special treatments, you can imagine them into basic primary or primary primitive types, which will be used frequently when programming; it is specifically treated because of NEW to create certain objects, especially It is a small simple variable, efficiency is not particularly high, because New will put the object in the stack; for these types, Java provides a similar approach to C and C , that is, do not create these variables with NEW, and Yes, create an automatic variable, this variable is not a reference, why not reference? Because of the specific value, it is placed in the stack, not the memory heap, thereby achieving higher efficiency;

Java decided in advance, the size of each primary type, just like in most languages; this size does not change as you change the hardware platform operating system, and the size cannot be changed is that the Java program has strong portability. one of the reasons;

Java data types are divided into three categories, namely,, name, character, and numeric, and numeric types are intellectual and floating point; relative to data type, Java variable type is Boolean; character type Char; integer, short, int, long; floating-point float, double. Four of four integer variables and two floating-point variables correspond to different precision and ranges, respectively.

Main Type Size Minimum Maximum Package Type Boolean - - - Boolean Char 16-Bit Unicode 0 Unicode 216- 1 Character BYTE 8-BIT-128 127 BYTE SHORT 16-BIT -215 215? 1 Short Int 32-bit -231 231? 1 INTEGER Long 64-bit -263 263? 1 long float 32-bit IEEE754 IEEE754 FLOAT DOUBLE 64-bit IEEE754 IEEE754 Double Void - - - Void Note:

1, all numerical types are symbolically negative;

2, the size of the Boolean Boolean type does not clearly regulate, as long as you can accommodate TRUE or FALSE, it is OK;

The original data type also has its own packaging Wrapper class, which means that if you want to make a non-main object in the stack indicate that the main type, you should use the corresponding package; for example:

CHAR C = 'x';

Character C = New Character (C);

Can also be used directly:

Character C = New Character ('x');

1.2.2. Java packaging class

The so-called packaging class is that we can directly represent the simple type of variables as a class. When performing mutual conversion of variable types, we will use these packaging classes.

Java has six packaging classes, namely Boolean, Character, Integer, Long, Float and Double, which we can see them from the literal, which correspond to Boolean, CHAR, INT, LONG, FLOAT, and DOUBLE. And String itself is class. So there is no concept of packaging classes.

1.2.3. Basic type, package and its interchange

1.2.3.1. Mutual conversion in integer, real, character variable

In Java integer, real, character type is considered as the same type of data, these types are low-level to advanced respectively (byte, short, char) int ?? long ?? Float ?? Double, low variables can be directly Convert to advanced variables, for example, the following statement can pass directly in Java:

BYTE B;

INT i = B;

When the advanced variable is converted to a low-level variable, the situation will be complex, you can use forced type conversion. That is, you have to use the following statement format:

INT I;

BYTE B = (Byte) i;

Imagine that this conversion may definitely lead to a decline in overflow or accuracy, so we do not recommend this conversion.

The assignment of floating point is DUBLE type, if f or f is added after floating point numbers, then D or D is Double, the floating point number of scientific counting is also Double type And the Double's precision is higher than Float, and a high-precision Double assignment is required to enforce type conversion when a low-precision Float is required, and it is not necessary.

Float f = 11.1; (is wrong)

1.2.3.2. Simple type variables and mutual conversion between packaging classes

Simple type variables are converted to the corresponding packaging class, which can utilize the constructor of the package class. That is: Boolean value;

Character (char value);

INTEGER (INT VALUE);

Long (long value);

Float value;

Double (Double Value)

In each package class, a method of total tab is ×× value () to obtain its corresponding simple type data. With this method, the conversion between different numerical variables can be achieved, for example, for a double-precision real type, intValue () can obtain its corresponding integer variable, while DoubleValue () can get its corresponding double precision Type variable.

1.2.3.3. String class and other data types of mutual conversion

For these packaging classes above, in addition to Character, there are configuration functions that can directly use string parameters, which makes us convert String class to these data types, which is simpler, namely:

Boolean (String S);

Integer (String S);

Long (string s);

FLOAT (String S);

Double (String S);

Now we have a characteristic variable, in fact, the String class can be understood as a CHAR type array, so we can find such a method in the String class to implement this conversion: Charat (int index) can get a string class The characters in a location, TocharaRray () can convert the entire String class into an array of char.

For all packaging classes, there is a method called toString () to convert it into a corresponding String class, and for integer and long integrings, you can also use TobinaryString (Int i), tohexString (INT i) TOOCTALSTRING (INT i) is converted to the String class in binary, hexadecimal and octal form, respectively.

1.2.3.4. Character type Directly converted to other data types

Converting the character variable to the numerical variable actually has two corresponding relationships, in the conversion of our first part, actually converts it to the corresponding ASCII code, but we sometimes need another Conversion relationship, for example, '1' means the value 1, not its ASCII code, for this conversion, we can use the CHARACTER's GetNumericValue (CHAR CH) method.

Package com.mint.sys.util; public class objconvert {private objconvert () {} / ***************************** Basic Type and Package Mutual conversion * *************** / ** * Translate the Integer wrapper into int base type * @Param I integer * @return int * / public static int integert (Integer i) {ix (I == null) Return 0; INT i = I.intValue (); returni} / ** * Translate int base type into an Integer packager * @Param I int * @return integer * / public static integer INTTOINTEGER (INT i) {INTEGER I = New Integer (i); Return i;} / ** * Transforms the Charater Package Object to CHAR Basic Type * @Param C Character * @Return Char * / Public Static Char CHARATERTOCHAR (JAVA .lang.Character C) {if (c == null) Return '0'; char c = c.charvalue (); return c;} / ** * Translate the basic type of CHAR to CHARATER wrapper object * @Param C Char * @Return Character * / public static character chartochar (char c) {Character C = New Character ('c'); Return C;} / ** * Translate the LONG wrapper object to long basic type * @Param l Long * @ RETURN long * / public static long longtolong (long L) {if (l == null) {RETURN 0L;} long l = l.longvalue (); returnit} / ** * Translate the LONG basic type to long packaging Object * @Param L long * @return long * / public static long line = new long (l); return L;} / ** * Translate FLOAT wrapper object to float Basic Type * @Param f float * @Return float * / public static float floattofloat (float f) {if (f == null) {return -1f;} float f = f.floatValue (); returnif;} / ** * Float basic type translates to FLOAT wrapper object * @Param f float * @

Return float * / public static float floattofloat (float f) {float f = new float (f); returnif;} / ** * Translate Double wrapper object to double base type * @Param D double * @return double * / Public static double doubleetodouble (DOUBLE D) {if (d == null) Return 0D; double d = d.doubleValue (); return d;} / ** * Translate Double Basic Type to Double Package Object * @Param Double * @Return Double * / public static double DouBletoDouble (double d) {double d = new double (d); return D;} / ** * Transform Boolean wrapper object to Boolean basic type * @Param B Boolean * @return boolean * / public static boolean booleantoboolean (boolean b) {if (b == null) Return false; boolean b = B.BooleanValue (); return b;} / ** * Translate Boolean basic type to Boolean object type * @Param B Boolean * @Return Boolean * / Public Static Boolean Booleantoboolean (Boolean B) {Boolean B = New Boolean (B); Return B;} / *************** *********** Mutual conversion with String types ************************* ****** / ** * Translate String object to int base type * @Param s string * @return int * / public static int stoi (string s) {INT i = -1; if (s == NULL || S.trim (). Length () == 0) {RETURN I;} try {i = integer.parseint (s);} catch (exception e) {debug.print ("Stirng Convet To int Error! "); Return i;} RETURN I;} / ** * Translate int type to string * @Param I int * @Return string * / public static string itos (int i) {string s = INTTOINTEGER (i) .tostring (); Return s;} / ** * Translate String Type to Long Type * @Param s string * @

Return long * / public static long stol (string s) {long L = -1L; if (s == null || s.trim (). Length () == 0) {Return L;} Try {L = long .PARSelong (s);} catCH (Exception E) {debug.println ("String Convert to Long Error!"); Return L;} Return L;} / ** * Translate the long type to string type * @Param L Long * @return string * / public static string LTOS (long L) {string s = longtolong (l) .tostring (); return s;} / ** * Translate String Type to float type * @Param s string * @ Return float * / public static float stof (string s) {float f = -1f; if (s == null || s.LENGTH () == 0) {RETURN F;} try {f = float.parsefloat (s );} Catch (Exception E) {Debug.println ("String Convert to Float Error"); returnif;} return f;} / ** * Translate FLOAT type to string type * @Param f float * @Return String * / Public static string ftos (float f) {string s = floattofloat (f) .tostring (); return s;} / ** * Transform String Type to DO Uble type * @Param s string * @Return double * / public static double stod (string s) {double d = -1d; if (s == null || s.Length () == 0) {RETURN D;} Try {d = double.parsedouble (s);} catch (exception e) {debug.println ("string convert to double error"); return D;} return D;} / ** * Transform Double type to String Type * @Param D Double * @return string * / public static string dtos (double d) {string s = doubletoDouble (d) .tostring (); return s;} / ** * test * @

Param args string [] * / public static void main (string [] args) {integer i = new integer (10); int i = integertOint (i); system.out.println ("Convert Integer to int: i );}} 1.2.4. High precision

Java offers two classes that specifically despite high-precision operations Biginteger and BigDecimal, although they can be roughly divided into the same categories as the packaging, but there is no corresponding primary type; these two classes have their own one A series of methods, similar to the operation of our main type, that is to say, can do it like Biginteger and BigDecimal with Biginteger and BigDecimal, rather than using operators. In addition, due to more, the calculation speed will slow down, and we sacrifice the speed, but in exchange for accuracy.

1.2.4.1. High precision integer Biginteger

Biginteger supports an integer of any precision, that is, we can accurately represent an integer value of any size; it will not lose any information during the operation;

There are all basic arithmetic operation methods in the Biginteger class, such as add, minus, multiply, division, and bit operations that may be used, different or non-left, right movement, etc. Here are some examples of methods: Of course, if you need to have more methods, you can check the Java API.

Package com.might.test; import java.math. *; / ** * *

title: open source, open *

description: Opeansource *

Copyright: Copyright c) 2004 *

Company:? Haishu * @Author Haitang Ming * @version 1.0 * / public class bigintegertest {public bigintegertest () {} / ** * Test Biginteger * / Public Static Void Testbiginteger () {Biginteger Bi = New Biginteger ("888"); // Multiply: Multiplication Biginteger Result = BI.MULTIPLY (New Biginteger ("2")); System.out.Println (Result); // Divide: Disult = bi.divide (New Biginteger ("2"))); system.out.println (Result); // add: add result = bi.add (New Biginteger ("232")); System.out.Println (RESULT); // Subtract: subtraction result = bi.subtract (New Biginteger ("23122")); System.out.Println (Result); Result = bi.shiftright (2); system.out.println (Result) } Public static void main (string [] args) {testbiginteger ();}} 1.2.4.2. High precision floating point BigDecimal

Some non-integer values ​​(such as a few dollars and a few decisions such as a few decisions) need to be precise. The floating point is not a precise value, so use them will result in rounding errors. Therefore, using floating point numbers to try to indicate that the quantity of the amount of money is not a good idea. The use of floating point is used for dollar and coding calculations to get catastrophic consequences. The floating point number is best used to represent the value of the measured value, which is not accurate from the beginning.

From JDK 1.3, Java developers have another numerical representation to express non-integers: BigDecimal. BigDecimal is a standard class that does not require special support in the compiler, which can represent the decimal of any precision and calculate them. Internally, the value of any precision can be used to represent the value of any range and a conversion factor, and the conversion factor indicates how many bits of the left-shifter decimal point, thereby obtaining the value within the desired range. Therefore, in the form of a number represented by BigDecimal is UnscaledValue * 10-Scale.

Method for adding, minus, multiplication, and division provides arithmetic operations for BigDecimal values. Since the BigDecimal object is not variable, each of these methods produces a new BigDecimal object. Therefore, because the cost of creating an object, BigDecimal is not suitable for a large number of mathematical calculations, but the purpose of designing it is to accurately represent the decimal. If you are looking for a value that can accurately indicate such a currency, BigDecimal can be better enough to do this task. As the floating point type, BigDecimal also has some strange behavior. Especially if you use the equals () method to detect whether the values ​​are equal, be careful. The equals () method believes that both BigDecimal values ​​indicating the same number but different (for example, 100.00 and 100.000) are unequal. However, the Compareto () method will think that both numbers are equal, so compare () instead of equals () should be used when comparing two BigDecimal values ​​from the value.

There are also some cases, and the decimal operation of any precision is still unable to indicate precise results. For example, 1 is divided into decimal decimal in which an infinite cycle is generated. 111111 ... For this reason, BigDecimal allows you to explicitly control. The MovePointLeft () method supports the precise division of the power of 10.

For BigDecimal, there are several available constructor. One of the constructor is used as input, and the other is an integer and conversion factor as an input, and there is an input as an input in a decimal String. Be careful with the BigDecimal (Double) constructor, because if it does not understand it, a rounding error is generated during the calculation process. Use constructor based on integer or string.

If you use the BigDecimal (Double) constructor, it is not appropriate to pass to the JDBC setBigDecimal () method, it will cause an exception in the JDBC driver. For example, consider the following JDBC code, the code wants to store the number 0.01 to the decimal field:

PreparedStatement PS =

Connection.PrepareStatement ("INSERT INTO FOO SET NAME = ?, value =?");

Ps.setstring (1, "penny");

Ps.SetBigDecimal (2, New BigDecimal (0.01));

ps.executeUpdate ();

When performing this seemingly harmless code, it will throw some confusing anomalies (depending on the specific JDBC driver), because the two precision approximation of 0.01 will result in a large conversion value, which may make JDBC The driver or database is confused. The JDBC driver will produce an exception, but may not indicate where the code is actually wrong, unless the limitations of binary floating point numbers. Instead, use BigDecimal ("0.01") or BigDecimal (1, 2) to construct BigDecimal to avoid such problems, because both methods can accurately represent decimals.

Package com.mings.sys.util; import java.math.bigdecimal; / ** * *

title: open source, open source, open *

Description: Opeansource *

Copyright: Copyright (c) 2004 *

Company:? Haishu * @Author Haitang Ming * @Version 1.0 * / public class bigdecimalutil {// Default division operation accuracy, and how many private of the decimal point Static Final Int DEF_DIV_SCALE = 2; // This class cannot instantiate private bigdecimalutil () {} / ** * 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 ();} / ** * Provides 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 ();} / ** * Provides 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 ();} / ** * Provides (relatively) accurate division operation, when there is an endless situation, How much is exactly to * decimal points, and the numbers in the future are rounded. * @Param V1 Demand * @Param V2 divisor * @Return two parameters of business * / public static double div (double V1, double v2) {Return Div (V1, V2, DEF_DIV_SCALE);} / ** * provides (relative ) Accurate division operation. When an endless case occurs, the Scale parameter refers to * fixed precision, and the number will be rounded.

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

New Post(0)