• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Multiplication Issue when Variables as Double Datatype

 
N.Senthil Kumar
Ranch Hand
Posts: 50
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
package test1;

public class TestApp {

public static void main(String[] args) {

double a = 0.43;
double b = 0.1;
System.out.println(a * b);

}
}

The Output shows 0.043000000000000003.

But the 0.43 * 0.1 is 0.043.

May i know why the Value have 3 at last in the Output ----> 0.04300000000000000 3.

Thanks in Advance.
 
Vivek Singh
Ranch Hand
Posts: 92
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Use float it will work.
 
Hunter McMillen
Ranch Hand
Posts: 492
Firefox Browser Linux VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Do you need that much precision? A 3 in that far down seems pretty negligible to me.


-Hunter
 
Embla Tingeling
Ranch Hand
Posts: 237
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
N.Senthil Kumar wrote:May i know why the Value have 3 at last in the Output ----> 0.04300000000000000 3.


Not every decimal number (which humans prefer) can be exactly converted to a binary number (which computers prefer). So conversions back and forth between number systems tend to produce small errors.

Also the number of bits used to represent numbers internally in the computer is fixed. As you probably know a float uses 32 bits and a double 64. This means that when arithmetical operations are performed, the result may not be exact. So operations on numbers in fixed-size representation also tend to introduce small errors.

The result is what you see in your example. The combination of conversion errors and fixed-size arithmetic errors show up as a "ripple" in the result.

These kinds of errors are fundamental to digital computers so they will always be present. One way to handle them is to round the result of a calculation. As you can see the error is far smaller than the 2 digits of precision you've used in the input numbers. If you round the output to the same precision the error disappears and the result is "correct".

Also note that programmers must watch out so formulas they use don't magnify those small fundamental and unavoidable errors. Such formulas are called ill-conditioned and there's a whole branch of math called numerical mathematics which is dealing with that.
 
Ulf Dittmer
Rancher
Posts: 42967
73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Please UseAMeaningfulSubjectLine. You can edit the subject using the button.

As to your question, see #20 in the http://faq.javaranch.com/java/JavaBeginnersFaq.
 
N.Senthil Kumar
Ranch Hand
Posts: 50
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Friends,
Thanks for the Reply .
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic