Reputation: 4814
I heard that double
is a more precise datatype and I would like to see the result of double
with the help of following program but still it is giving variable result each time similar but not exact to float
.
What is the difference between float
and double
and when to use them in real time?
Can any body explain this scenario in simple terms
and specify the reason for this type of behaviour?
Thanks in advance :)
public class DoubleResult {
public static void main(String[] args) {
double number=1;
for(int i=0;i<5;i++){
number=number+0.1;
System.out.println(number);
}
}
}
output:
1.1
1.2000000000000002
1.3000000000000003
1.4000000000000004
1.5000000000000004
Upvotes: 0
Views: 86
Reputation: 37023
A computer's floating point unit works with base 2 binary and 0.2 can't be represented precisely in binary, it is called a repeater fraction. In base-2 only numbers with denominators that are powers of 2 are terminating, which I think is only .25, .50, and .75, which is why 6.5 shows up as "same".
Imagine you had two decimal types, one with six significant digits, and one with sixteen.
What value would you use to represent pi for each of those types? In both cases you'd be trying to get as close to a number which you couldn't represent exactly - but you wouldn't end up with the same value, would you?
It's the same for float(32 bits) and double(64 bits) - both are binary floating point types, but double has more precision than float. so if you need precision then go for double.
See this for more details
Upvotes: 0
Reputation: 10978
Both float
and double
are floating points. float
is a single-precision (32 bit) floating point whereas double
is a double-precision (hence the name) (64 bit)
Name Width in Bits Range
double 64 1.7e–308 to 1.7e+308
float 32 3.4e–038 to 3.4e+038
you can see this answer for a more precise description of the precision issue with floating points
Upvotes: 1