Addition of doubles (newbie question)
Hi. In subtracting one double from another, namely 45.32 - 45.31, I get a result of 0.00999999999999801. According to all the math I've ever learned, the answer should be .01.
I asked my professor about this, and his response was that "45.31 may be a repeating decimal." To which I responded, "I have no idea what that means." I tried another forum, where someone treated me like I was a complete moron.
I just don't understand what's happening, and if someone could explain it to me very simply, I'd greatly appreciate it.
Thank you.
Re: Addition of doubles (newbie question)
OP has been given a link and an explanation already and became abusive. Do not waste your time with this idiot.
This thread has been cross posted here:
http://www.java-forums.org/new-java/42781-double-subtraction.html
Although cross posting is allowed,
for everyone's benefit, please read:
Java Programming Forums Cross Posting Rules
The Problems With Cross Posting
Re: Addition of doubles (newbie question)
Hello archyb,
It would be worth doing some reading about repeating decimals. There is lot's of information online.
Heres the gist of it though:
Quote:
A decimal representation of a real number is called a repeating decimal (or recurring decimal) if at some point it becomes periodic: there is some finite sequence of digits that is repeated indefinitely. For example, the decimal representation of 1/3 = 0.3333333... (spoken as "0.3 repeating", or "0.3 recurring") becomes periodic just after the decimal point, repeating the single-digit sequence "3" infinitely. A somewhat more complicated example is 3227/555 = 5.8144144144..., where the decimal representation becomes periodic at the second digit after the decimal point, repeating the sequence of digits "144" infinitely.
The link provided in your other forum post is also useful:
What Every Computer Scientist Should Know About Floating-Point Arithmetic
I know it's an awful lot of reading and to a beginner it can be very daunting but even just a quick read will help you pick up some basic information that helps lay the foundation for the knowledge you need to acquire.
I also suggest reading - Java theory and practice: Where's your point?
You can round your answer to get the expected output:
Code Java:
public class DoubleTest {
/**
* JavaProgrammingForums.com
*/
public static void main(String[] args) {
double x = 45.32;
double y = 45.31;
double answer = (x - y);
answer = Math.round(answer*100)/100.0d;
System.out.println(answer);
}
}