When testing the output of a variable of type double, with expected results = 48.66573405, I am getting an actual result = 48.6657.

Why is the expected result being rounded when the whole idea of using type double is to increase the precision of your calculations?

Thanks
FWD

I expect that you wrote somthing like this: std::cout<<"result == "<<a<<std::endl; . The problem with that is the default precision, for output, is 6. The number itself is of a higher precision.
If you write this

#include <iostream>
#include  <iomanip>   
 
int main()
{
double a=1.2345678901234567890;

std::cout<<std::setprecision(20);
std::cout<<"results ="<<a<<std::endl;
// Not all numbers are now in precision 20.

The following code give you something like : 1.1234567890123456912
That is because [for my 64 bit machine -- sizeof(double) == 8 bytes] the precision of double is about 14/15 decimal places. [and I got lucky with the roundoff for the 16th ;) ]


You will get more decimal points and a bigger exponent range if you use long double. If you need a larger precision for something, then there is the gmp [gnu multiple-precision library] http://gmplib.org/, which is only limited by your computer memory and speed.

Overall I am normally very very disappointed with the way that formating is done in C++. I basically rely on the boost::format http://live.boost.org/doc/libs/1_39_0/libs/format/doc/format.htmlsystem which is much more printf like but with slightly more type checking, and slightly better error messages.

Edited 5 Years Ago by StuXYZ: n/a

I expect that you wrote somthing like this: std::cout<<"result == "<<a<<std::endl; . The problem with that is the default precision, for output, is 6. The number itself is of a higher precision.
If you write this

#include <iostream>
#include  <iomanip>   
 
int main()
{
double a=1.2345678901234567890;

std::cout<<std::setprecision(20);
std::cout<<"results ="<<a<<std::endl;
// Not all numbers are now in precision 20.

The following code give you something like : 1.1234567890123456912
That is because [for my 64 bit machine -- sizeof(double) == 8 bytes] the precision of double is about 14/15 decimal places. [and I got lucky with the roundoff for the 16th ;) ]


You will get more decimal points and a bigger exponent range if you use long double. If you need a larger precision for something, then there is the gmp [gnu multiple-precision library] http://gmplib.org/, which is only limited by your computer memory and speed.

Overall I am normally very very disappointed with the way that formating is done in C++. I basically rely on the boost::format http://live.boost.org/doc/libs/1_39_0/libs/format/doc/format.htmlsystem which is much more printf like but with slightly more type checking, and slightly better error messages.

Thanks StuXYZ. Great answer and explanation. Question answered!

FWD

This question has already been answered. Start a new discussion instead.