hi, I already know how to use setprecision but the function wont let the round go up past 16.

#include<iostream>
#include<stdio.h>
#include<math.h>
#include<iomanip>
using namespace std;
int main ()
{
    double pi = 3.14159265358979323846264338327950288419716939937510;
    cout << setprecision(50) << pi << endl;
    system("pause");
}

the output is just 3.1415926535897931 the code to force it to go past 16 would be something like this:

#include<iostream>
#include<stdio.h>
#include<math.h>
#include<iomanip>
using namespace std;
int main ()
{
    double pi = 3.14159265358979323846264338327950288419716939937510;
    cout << force_max_digits_setprecision(50) << pi << endl; //I just added "force_max_digits_"
    system("pause");
}

any solutions? Thanks.

Recommended Answers

All 4 Replies

Run the following code to see how many digits your double is actually holding.

#include <iostream>
#include <ostream>
#include <limits>

int main()
{
    typedef std::numeric_limits< double > dl;

    using namespace std;

    cout << "double:\n";
    cout << "\tdigits (bits):\t\t" << dl::digits << endl;
    cout << "\tdigits (decimal):\t" << dl::digits10 << endl;
    cin.get()
    return 0;
}

how is that program supposed to help me? when i run the program, the output is just "double:
digits (bits): 53
digits (decimal): 15"

That means that you can only hold 15 digits after the decimal place. If you need more precision than that you will need to look into using a math library.

The definition of the IEEE double-precision format is eight bytes (MSB to LSB):

seee eeee   eeee emmm   mmmm mmmm   ...   mmmm mmmm

where s is a sign bit (1 is negative, 0 is positive), e is a 12-bit signed integer exponent (ranging from -2048 to 2047), and m is the remaining 51 bits, the fractional mantissa following an implicit "1.", so that the final value is

(1 - 2*s) * 1.m * (2^(e-2048))

Some values are necessarily reserved to indicate overflow, underflow, +/- infinity, and the always hilarious magical NaN constant (which has a tendency to flourish in unchecked linear algebra code :) ).

But the bottom line is, including the leading 1, you can store only 52 significant binary digits, and at ~10 bits to represent a trio of decimal digits, that comes to a little over 15 decimal digits that can be meaningfully represented in the decimal +- N.NNNNN * 10^e notation.

If you need more precision than a double provides, then you will need to use (or create, if you're bored) a higher-precision math library. I believe there are options for arbitrary precision (at the cost of storage and computation). Wikipedia provides a large list of options, maybe something will fit your needs (if other than idle curiosity).

Enjoy!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.