user6136611
user6136611

Reputation:

How do I set precision to 100 digits in c++?

I am sorry, I have a very basic question.

Here is a very simple calculation, an integer (22) divided by another integer (7). I would like the c++ code use exactly 100 digits of precision both in the actual calculation inside the code and in the output value. Using the Maple program, I get

restart;
Digits:=100;
evalf(22/7);

And the answer I get is,

3.142857142857142857142857142857142857142857142857142857142857142857142857142857142857142857142857143

But I use the following c++ code and get something different answer. This simply adds zeros after few actual digits, which is completely wrong. Below is my c++ code.

#include <iostream>
 using namespace std;
 int main()
 {
     cout << fixed;
     cout.precision(100);
     cout << "22/7 = " << 22/(double)(7) << endl;
     return 0;
}

Upvotes: 3

Views: 362

Answers (1)

Slava
Slava

Reputation: 44238

Using the Maple program, I get

Maple is a special tool that beside others:

Support for symbolic and numeric computation with arbitrary precision

On another side C++ is a general purpose programming language. As a language it supports floating point arithmetic which has limited precision. You cannot expect to throw arbitrary precision there and expect the same result as you get in Maple. So you need to use an arbitrary precision library (which is not part of standard C++) or switch to a different language that supports it by design.

Upvotes: 5

Related Questions