wood burning stoves 2.0*
The moose likes Java in General and the fly likes A problem with a substract Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "A problem with a substract" Watch "A problem with a substract" New topic
Author

A problem with a substract

Rafael Gutierrez
Greenhorn

Joined: Jun 03, 2003
Posts: 3
Hello everybody
In my code I have the next operations:
double d1 = 4.74;
double d2 = 4;
System.out.println(d1-d2);
and the printed result is '0.7400000000000002'.
Somebody knows why?


Rafa
Wayne L Johnson
Ranch Hand

Joined: Sep 03, 2003
Posts: 399
Every 'real' value in Java--float and double--is stored in a binary representation as defined by the IEEE 754 standard. As such, many numbers may be only an approximation, and so you'll see small rounding errors such as the one you pointed out.
Think of it this way. If you add the fractions 1/3 + 2/3 you expect to get 3/3, or 1. However if you look at these in terms of decimal arithmetic you could get 0.3333333333 + 0.6666666666 = 0.9999999999.
If you'd like to get more information [than you'll probably ever need] on this subject, check out Floating Point Arithmetic on Sun's web site.
Please note that this problem isn't specific to Java: you can find similar problems in almost any programming language that supports floating point arithmetic.
[ September 05, 2003: Message edited by: Wayne L Johnson ]
Thomas Paul
mister krabs
Ranch Hand

Joined: May 05, 2000
Posts: 13974
Very few fractions can be properly represented in floating point. Even that double that you put 4.74 into doesn't have the actual value 4.74. The println for double is designed to not show the actual contents but to truncate it off. Look at this code:

This will print the actual way that 4.74 is stored in a double:
4.7400000000000002131628207280300557613372802734375
[ September 05, 2003: Message edited by: Thomas Paul ]

Associate Instructor - Hofstra University
Amazon Top 750 reviewer - Blog - Unresolved References - Book Review Blog
Thomas Paul
mister krabs
Ranch Hand

Joined: May 05, 2000
Posts: 13974
By the way, this program will do the correct calculation but notice that you have to use Strings in the constructor to get it to work right.

[ September 06, 2003: Message edited by: Thomas Paul ]
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: A problem with a substract
 
Similar Threads
Double Boolean Operations
pls help on NaN
Hi
if(0.0 == -0.0) - Sample question
== operator comparisons