JAVA basics: Floating Point Number analysis and reflection in Java
Source: Internet
Author: User
JAVA basics: Floating Point Number Analysis and Thinking in Java-Linux general technology-Linux programming and kernel information. The following is a detailed description. Floating Point Numbers are classified into single precision and double precision. The single precision and double Precision in Java are float and double, respectively. Do you know how float and double are stored?
Float occupies 4 bytes and double occupies 8 bytes. For convenience, we will only discuss the float type here.
Float is actually the same as the size of an int type, a total of 32 bits, the first sign, 2-9 represents the index, the next 23 bits represent the fractional part. Here not much said, please refer to: http://blog.csdn.net/treeroot/archive/2004/09/05/95071.aspx
Here is only one example. If you want to learn more about the storage format of floating point number 0.1, run this program first.
Public class Test {
Public static void main (String [] args ){
Int x = 0x3d800000;
Int I = 1 <22;
Int j = 1 <4;
Float f = 0.1f;
Int y = Float. floatToIntBits (f );
Float rest = f-(float) 1)/j;
While (I> 0 ){
J <= 1;
Float deta = (float) 1)/j;
If (rest> = deta ){
Rest-= deta;
X | = I;
}
I >>= 1;
}
Pr (x );
Pr (y );
}
Static void pr (int I ){
System. out. println (Integer. toBinaryString (I ));
}
Program description:
Int x = 0x3d80000;
Because the floating point representation is 1. f * 2n-127 we want to represent 0.1, you can know the n-127 =-4, to n = 123
If the symbol is positive, we can see that the first 9 is 001111011, so we do not consider the next 23 decimal places, so we first assume that x = 0x3d800000;
Int I = 1 <22;
I initially sets the first 23rd bits from the right to 1, which is the 10th bits of x.
Int j = 1 <4;
I initially is 4, because the n-127 is-4, here is to calculate its reciprocal.
Float f = 0.1f;
Int y = Float. floatToIntBits (f );
Y is its 32-bit representation.
Float rest = f-(float) 1)/j;
This rest indicates the rest of 1 in 1.f, that is, 0.f.
While (I> 0 ){
J <= 1;
Float deta = (float) 1)/j;
If (rest> = deta ){
Rest-= deta;
X | = I;
}
I >>= 1;
}
This loop is used to calculate the 23th decimal part. If rest is not smaller than deta, this bit can be set to 1.
Nothing else. The input results are the same. It can be said that the floating point number 0.1 is definitely not accurate, but 0.5 can be accurately expressed. Why.
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.