-1

Possible Duplicate:
Floating point arithmetic not producing exact results in Java
Float numbers in Java

Please see Code Below.

public class TestSum {

public static void main(String[] args) {
    float a = 4.8f;//try with 4.7f
    float b = 4.5f;//try with 4.6f
    double sum = a + b;
    System.out.println(sum);
 }
}

(4.8f+4.5f) sum=9.300000190734863

But when, i tried (4.7f+4.6f) it gives sum = 9.299999237060547 Again,

(1.8f+1.5f) sum=3.299999952316284.
(1.7f+1.6f) sum=3.3000001907348633.

But,

(2.8f+2.5f) sum=5.300000190734863.
(2.7f+2.6f) sum=5.300000190734863.

I want to Understand, how this works. Thanks in advance.

Community
  • 1
  • 1
Manjeet
  • 949
  • 14
  • 23

3 Answers3

3

Your problem is common to all programming languages, and it is due to the finite precision of floating point numbers.

Lorenzo Dematté
  • 7,638
  • 3
  • 37
  • 77
1

I want to understand how this works.

See the info. & links (listed below) on the floating point tag Wiki.

What's best solution for this then...?

BigDecimal, or more commonly, formatting the output using DecimalFormat.

Community
  • 1
  • 1
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
0

Thanks Everyone For Helping me here.

But i asked this question, to understand why doesn't this happens in Python,Ruby or JavaScript, but in Java.

I think one Possible solution for precision is to go with double

   public class TestSum {
   public static void main(String[] args){
   double a = 4.8d;
   double b = 4.5d;
   double sum = a + b;
   System.out.println(sum);
   }
   }
Manjeet
  • 949
  • 14
  • 23
  • *"I think one Possible solution for precision is to go with double"* No. Try more combinations. – Andrew Thompson Jan 23 '13 at 11:12
  • @AndrewThompson Yeah you are right. It Doesn't work either. What's best solution for this then...? – Manjeet Jan 23 '13 at 11:32
  • 2
    [`BigDecimal`](http://docs.oracle.com/javase/7/docs/api/java/math/BigDecimal.html), or more commonly formatting the output using [`DecimalFormat`](http://docs.oracle.com/javase/7/docs/api/java/text/DecimalFormat.html). – Andrew Thompson Jan 23 '13 at 11:36
  • 1
    This makes the question more precise. It DOES happen in Python,Ruby or JavaScript :) It does happen in all programming languages, if you are using floating-point math. And it happens at different levels; using single-precision floats makes the problem apparent in more cases, while using double-precision floats may hide it in many cases. And I suspect that most of the dynamic languages you mentioned use by default double-precision floating point numbers – Lorenzo Dematté Jan 23 '13 at 11:42
  • 1
    As @AndrewThompson pointed out, going from floating point numbers to fixed point-precise representations will solve the precision problem, at the expense of performance of course (I would not use it in games, for example) – Lorenzo Dematté Jan 23 '13 at 11:43