Strange rounding of numbers when reading in from text file C++ - c++

I have a text line containing only the following lines.
0.01180994648909809 0.0118339243907452 0.01153905217670122
0.0376759911531237 0.03771224865527065 0.03765957194275842
I used the following code to read this data and output it to terminal
using namespace std;
int main(int argc, char *argv[])
{
ifstream infile(argv[1]);
string line;
double a,b,c;
while(getline(infile,line))
{
istringstream iss(line);
iss >> a >> b >> c;
cout<<a<<"\t"<< b << "\t"<<c<<endl;
}
return 0;}
The output I got was
0.0118099 0.0118339 0.0115391
0.037676 0.0377122 0.0376596
Why is it that in the output the numbers have been rounded to 7 digits after the decimal? Is this rounding performed only while displaying to standard output?

EDIT: Moving the proposed solution at top of the relevant information.
You can use set::precision to see the proper precision.
Apart from the answer above, It is important to note that Whenever, You use float and decimal numbers Rounding Errors & Precision are an definite factor.
What is an Precision Error?
The precision of a floating point number is how many digits it can represent without losing any information it contains.
Consider the fraction 1/3. The decimal representation of this number is 0.33333333333333… with 3′s going out to infinity. An infinite length number would require infinite memory to be depicted with exact precision, but float or double data types typically only have 4 or 8 bytes. Thus Floating point & double numbers can only store a certain number of digits, and the rest are bound to get lost. Thus, there is no definite accurate way of representing float or double numbers with numbers that require more precision than the variables can hold.
What is a Rounding Error?
There is a non-obvious differences between binary and decimal (base 10) numbers.
Consider the fraction 1/10. In decimal, this can be easily represented as 0.1, and 0.1 can be thought of as an easily representable number. However, in binary, 0.1 is represented by the infinite sequence: 0.00011001100110011…
An example:
#include <iomanip>
int main()
{
using namespace std;
cout << setprecision(17);
double dValue = 0.1;
cout << dValue << endl;
}
This output is:
0.10000000000000001
And not
0.1.
This is because the double had to truncate the approximation due to it’s limited memory, which results in a number that is not exactly 0.1. Such an scenario is called a Rounding error.
So be aware of these errors when you use floar or double.

Related

C++ Avoid Rounding Number

I know we can use setprecision to prevent a number to be rounded but what if I don't want to round all of my numbers in the list with the same decimal places? In other words, I want to keep my numbers the same as calculated and each number has its own decimal places.
For example: if we use setprecision(7) then it will give the output up to 7 decimal places for all numbers in my list. What if I have a list of different numbers with different decimal places such as 8 or 10 decimal places? Do I need to do setprecision for each of them? Is there any way to keep my numbers the same as the output after calculated? Ex:0.1234567, 0.123456789, 0.12345678910
#include<iostream>
#include<vector>
using namespace std;
int main()
{
vector<double> myVec{0.1234567, 0.123456789, 0.12345678, 0.12345678910};
for(int i = 0; i < myVec.size(); i++)
{
cout << myVec[i] << " ";
}
return 0;
}
Is there any way to keep my numbers the same as the output after calculated?
Not with floating point types such as double.
These are binary floating points, not decimal. Many exact finite decimal fractions will convert to infinite binary fraction, and rounding would happen. So after you do dobule d = 0.1234567, the variable d will not contain exactly 0.1234567, it is rather something close to 0.1234567 representable as double.
A way to deal with this is to have custom data types that are decimal fractions, with fixed or floating point, so that 0.1234567 could be represented exactly.

How to convert string to double with specified number of precision in c++

How to convert string to double with specified number of precision in c++
code snippet as below:
double value;
CString thestring(_T("1234567890123.4"));
value = _tcstod(thestring,NULL);
The value is coming as this:1234567890123.3999
expected value is:1234567890123.4
Basically you can use strtod or std::stod for the conversion and then round to your desired precision. For the actual rounding, a web search will provide lots of code examples.
But the details are more complicated than you might think: The string is (probably) a decimal representation of the number while the double is binary. I guess that you want to round to a specified number of decimal digits. The problem is that most decimal floating point decimal numbers cannot be exactly represented in binary. Even for numbers like 0.1 it is not possible.
You also need to define what kind of precision you are interested in. Is it the total number of digits (relative precision) or the number of digits after the decimal point (absolute precision).
The floating-point double type can not exactly represent the value 1234567890123.4 and 1234567890123.3999 is the best it can represent and that is what the result is. Note that floating point types (e.g. IEEE-754) can not exactly represent all real numbers, hence these use approximations for most cases.
To be more precise, according to IEEE-754 double-precision floating point format 1234567890123.4 is represented as the hexadecimal value of 4271F71FB04CB666, where in binary the sign bit is 0, the 11 exponent and 52 singificand bits are 10000100111 and 0001111101110001111110110000010011001011011001100110 respectively. So this results in the value of (-1)sign×2exponent×(1.significand bits) = 1×240×1.1228329550462148311851251492043957114219 = 1234567890123.39990234375.
Note that not even a 128-bit floating point would store the value exactly. It would still result in 1234567890123.39999999999999999999991529670527456996609316774993203580379486083984375. Maybe you should instead attempt to use some fixed-point or rational number types instead.
std::stod is generic and doesn't give this kind of manipulation. Thus, you have to craft something of your own, like I did below using std::stringstream and <iomanip> facilities:
double stodpre(std::string const &str, std::size_t const p) {
std::stringstream sstrm;
sstrm << std::setprecision(p) << std::fixed << str << std::endl;
double d;
sstrm >> d;
return d;
}
Live Demo
You cannot control the precision with which a decimal number is stored.
Decimal numbers are stored in binary using the floating point notation.
What you can do is to control the precision of what is displayed on outputting the number.
For example, do this to control the precision of the output to 2 digits -
std::cout << std::fixed;
std::cout << std::setprecision(2);
std::cout << value;
You can give any number for the precision.

why double and long double are giving different answer in the following program

This code is calculating the Nth term of a series which is defined as
Tn+2=(Tn+1)^2+Tn, where 1st and 2nd terms are given as a and b in the code.
#include<iostream>
#include<string>
using namespace std;
int main()
{
int a,b,n;
char ch[100];
cin>>a>>b>>n;
long double res[3];
res[0]=a,res[1]=b;
for(int i=n-2;i>0;i--)
{
res[2]=res[1]*res[1]+res[0];
res[0]=res[1];
res[1]=res[2];
}
sprintf(ch,"%.0Lf",res[2]);
cout<<ch;
return 0;
}
Input: 0 1 10
Output:
84266613096281242861568 // in case of double res[3];
84266613096281243385856 // in case of long double res[3];
correct output : 84266613096281243382112
Since it is going out of the range of integer, therefore I am using double/long double.
But the problem is I am getting different output for double and long double, while none of the intermediate values are having non zero digit after decimal point, so there should not be any rounding off, I guess.
while none of the intermediate values are having non zero digit after decimal point, so there should not be any rounding off, I guess.
This assumption is just plain wrong. All floating point numbers like double etc. are stored like
mantissa * 2^exponent
with a finite number of bits for both the mantissa and the exponent. So floating point numbers can store a fixed number of significant digits (for a double converted to decimal representation, around 16 usually). If a number has more digits before the decimal point, rounding will happen and the total rounding error gets bigger the more digits you need to "forget".
If you want more details on this, the most common floating point implementations follow the IEEE floating point standard.

Reading floating point values from a file drops all or part of the decimal part

I need to read floating-point values from a file.
Basic sample code of how I do this:
int main()
{
float number;
ifstream inputFile;
inputFile.open("testfile.dat");
inputFile >> number;
cout << number << endl;
return 0;
}
The first line in the file is: 13212.13131. But when I cout 'number' the displayed number is: 13212.1
The problem is part of the decimal gets dropped and in other cases all of it gets dropped. Why does this happen, and how can I solve this problem?
The point of reading the number from the file is to do mathematical calculations with it.
First, floating-point precision on output (for both std::cout and printf) is 6 decimal digits by default. You need std::setprecision() to get it print more digits. But you'll then get to the limit of float type.
On most systems float is IEEE-754 single precision, therefore it can only store about 7 digits of significant. The nearest to 13212.13131 is 1.3212130859375E4. If you need more precision, you must use double, which has about 15-16 digits of precision on most systems.
Read more: Is floating point math broken?
Try using std::setprecision():
cout << setprecision(14) << number << endl;
You will need to
#include <iomanip>
If that doesn't solve it you should try debugging it and see what the number actually is (13212.13131 or 13212.1).

Why comparing double and float leads to unexpected result? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
strange output in comparision of float with float literal
float f = 1.1;
double d = 1.1;
if(f == d) // returns false!
Why is it so?
The important factors under consideration with float or double numbers are:
Precision & Rounding
Precision:
The precision of a floating point number is how many digits it can represent without losing any information it contains.
Consider the fraction 1/3. The decimal representation of this number is 0.33333333333333… with 3′s going out to infinity. An infinite length number would require infinite memory to be depicted with exact precision, but float or double data types typically only have 4 or 8 bytes. Thus Floating point & double numbers can only store a certain number of digits, and the rest are bound to get lost. Thus, there is no definite accurate way of representing float or double numbers with numbers that require more precision than the variables can hold.
Rounding:
There is a non-obvious differences between binary and decimal (base 10) numbers.
Consider the fraction 1/10. In decimal, this can be easily represented as 0.1, and 0.1 can be thought of as an easily representable number. However, in binary, 0.1 is represented by the infinite sequence: 0.00011001100110011…
An example:
#include <iomanip>
int main()
{
using namespace std;
cout << setprecision(17);
double dValue = 0.1;
cout << dValue << endl;
}
This output is:
0.10000000000000001
And not
0.1.
This is because the double had to truncate the approximation due to it’s limited memory, which results in a number that is not exactly 0.1. Such an scenario is called a Rounding error.
Whenever comparing two close float and double numbers such rounding errors kick in and eventually the comparison yields incorrect results and this is the reason you should never compare floating point numbers or double using ==.
The best you can do is to take their difference and check if it is less than an epsilon.
abs(x - y) < epsilon
Try running this code, the results will make the reason obvious.
#include <iomanip>
#include <iostream>
int main()
{
std::cout << std::setprecision(100) << (double)1.1 << std::endl;
std::cout << std::setprecision(100) << (float)1.1 << std::endl;
std::cout << std::setprecision(100) << (double)((float)1.1) << std::endl;
}
The output:
1.100000000000000088817841970012523233890533447265625
1.10000002384185791015625
1.10000002384185791015625
Neither float nor double can represent 1.1 accurately. When you try to do the comparison the float number is implicitly upconverted to a double. The double data type can accurately represent the contents of the float, so the comparison yields false.
Generally you shouldn't compare floats to floats, doubles to doubles, or floats to doubles using ==.
The best practice is to subtract them, and check if the absolute value of the difference is less than a small epsilon.
if(std::fabs(f - d) < std::numeric_limits<float>::epsilon())
{
// ...
}
One reason is because floating point numbers are (more or less) binary fractions, and can only approximate many decimal numbers. Many decimal numbers must necessarily be converted to repeating binary "decimals", or irrational numbers. This will introduce a rounding error.
From wikipedia:
For instance, 1/5 cannot be represented exactly as a floating point number using a binary base but can be represented exactly using a decimal base.
In your particular case, a float and double will have different rounding for the irrational/repeating fraction that must be used to represent 1.1 in binary. You will be hard pressed to get them to be "equal" after their corresponding conversions have introduced different levels of rounding error.
The code I gave above solves this by simply checking if the values are within a very short delta. Your comparison changes from "are these values equal?" to "are these values within a small margin of error from each other?"
Also, see this question: What is the most effective way for float and double comparison?
There are also a lot of other oddities about floating point numbers that break a simple equality comparison. Check this article for a description of some of them:
http://www.cygnus-software.com/papers/comparingfloats/comparingfloats.htm
The IEEE 754 32-bit float can store: 1.1000000238...
The IEEE 754 64-bit double can store: 1.1000000000000000888...
See why they're not "equal"?
In IEEE 754, fractions are stored in powers of 2:
2^(-1), 2^(-2), 2^(-3), ...
1/2, 1/4, 1/8, ...
Now we need a way to represent 0.1. This is (a simplified version of) the 32-bit IEEE 754 representation (float):
2^(-4) + 2^(-5) + 2^(-8) + 2^(-9) + 2^(-12) + 2^(-13) + ... + 2^(-24) + 2^(-25) + 2^(-27)
00011001100110011001101
1.10000002384185791015625
With 64-bit double, it's even more accurate. It doesn't stop at 2^(-25), it keeps going for about twice as much. (2^(-48) + 2^(-49) + 2^(-51), maybe?)
Resources
IEEE 754 Converter (32-bit)
Floats and doubles are stored in a binary format that can not represent every number exactly (it's impossible to represent the infinitely many possible different numbers in a finite space).
As a result they do rounding. Float has to round more than double, because it is smaller, so 1.1 rounded to the nearest valid Float is different to 1.1 rounded to the nearest valud Double.
To see what numbers are valid floats and doubles see Floating Point