File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

floating point caculation problem

 
Stephen Suen
Ranch Hand
Posts: 34
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all,
I'm stucked. Here's a very simple class:
public class Multi{
public static void main(String args[]){
System.out.println("3.0 * 0.2 = " + (3.0 * 0.2));
}
}
The output is as follow:
3.0 * 0.2 = 0.6000000000000001
Why the result is wrong?
Any help will be appreciated.
Stephen
 
Tom Blough
Ranch Hand
Posts: 263
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The result is not wrong. Computers use binary numbers which don't always EXACTLY represent decimal numbers. Using decimal numbers, we cannot exactly represent 1/3. The decimal equivalent is 1.333333333 where the 3 repeats forever. The same thing happens with binary numbers. We can accurately represent 1/2 decimal as 0.1 binary. However, 0.2 decimal is represented as 0.0011001100110011 where the 0011 repeats forever.
When you cannot accurately represent the number in binary, small errors creep in when doing mathematical operations. What you are seeing is the result of those errors.
In science and engineering courses, you learn about a thing called "Significant Figures". Basically this says that your first number "3.0" has two significant digits. Your dividend "0.2" has one significant digit. Therefore, your result will only have one significant digit so the only portion of the result that is correct is the "0.6". There rest should be ignored.
Hope this helps.
[ October 30, 2003: Message edited by: Tom Blough ]
[ October 30, 2003: Message edited by: Tom Blough ]
 
Steve Morrison
Greenhorn
Posts: 6
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you want to cut down your answer to a certain number of places you can use DecimalFormat...for example
import java.text.*;
public class Multi{
public static void main(String args[]){
DecimalFormat df = new DecimalFormat("0.0");
System.out.println("3.0 * 0.2 = " + df.format(3.0 * 0.2));
}
}
...you can change the numbers in the quotes to give you the desired number of decimal places. Of course, I'm new at this so there might be an easier method to format your output.
[ October 30, 2003: Message edited by: Spiff Wilkie ]
 
Stephen Suen
Ranch Hand
Posts: 34
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks all.
Stephen
 
Zeeman Chen
Greenhorn
Posts: 9
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Great! That problem is also confusing me!
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic