简体   繁体   中英

issue in division with double values

why "2=" output is giving surprise results, please throw some light. what is the problem with double in this case.

any constraints for the division of double values.

Are there any options to avoid such things in c++.

#include<iostream.h>
#include<iomanip.h>
#include<math.h>
int main()
{
    double d1,d2,d3,d4,d5;
double d = 0.010000;

d1 = 1000000.28;
d2 = 10000000.28;
d3 = 100000000.28;
d4 = 1000000000.28;
d5 = 10000000000.28;

cout.precision(15);

cout<<"1="<<floor(d1/d)<<endl;
cout<<"2="<<floor(d2/d)<<endl;
cout<<"3="<<floor(d3/d)<<endl;
cout<<"4="<<floor(d4/d)<<endl;
cout<<"5="<<floor(d5/d)<<endl;

return 0;
  }

 o/p
 ====
1 = 1000000.28;
2 = 10000000.27;
3 = 100000000.28;
4 = 1000000000.28;
5 = 10000000000.28;

First, the output from your program is different from what you wrote in your question. The output is:

1=100000028
2=1000000027
3=10000000028
4=100000000028
5=1000000000028

not:

1 = 1000000.28;
2 = 10000000.27;
3 = 100000000.28;
4 = 1000000000.28;
5 = 10000000000.28;

Second, when you write double d = 0.010000 , d is not set to .01. It is set to a close value that is representable as a double . (In a good C++ implementation, it is set to the closest representable value.) In your C++ implementation, double is most likely an IEEE-754 64-bit binary floating-point value, and the closest representable value to .01 is 0.01000000000000000020816681711721685132943093776702880859375.

Similarly, when you write d2 = 10000000.28 , d2 is not set to 10000000.28. The closest representable value is 10000000.27999999932944774627685546875.

When you divide these, you get a number that is approximately, but slightly less than, 1000000028. The result of the division, rounded to a double , is 1000000027.99999988079071044921875. When you take the floor of that, the fraction is truncated, leaving 1000000027.

Avoiding or dealing with these issues requires knowledge about floating-point arithmetic and about the specific calculations you want to perform. In this case, we would need to know why you want to use floor .

The answer is um, complicated, as indicated by the comment by WhozCraig and the document he linked to.

The briefest answer I can give is to think of floating point numbers as very close approximations to the decimal counterparts (which c++ does not have the decimal data type).

A much easier way to understand this is through a great video by Jon Skeet at http://tekpub.com/blogs/video-releases/7964989-mastering-c-4-0-with-jon-skeet-7-decimals-and-floating-points . It is WELL worth the price of admission for the clarity. This video is specific to c# but the concepts are the same. I never knew this problem existed before watching the video.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM