3

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;
}
Christian Hackl
  • 27,051
  • 3
  • 32
  • 62
  • 14
    C++ doubles only hold ~14 digits accurately. It's not about display precision. – Mooing Duck Mar 07 '17 at 21:26
  • 5
    Try searching for an arbitrary precision library. – Some programmer dude Mar 07 '17 at 21:27
  • 1
    Possible duplicate of [Floating point inaccuracy examples](http://stackoverflow.com/questions/2100490/floating-point-inaccuracy-examples) – dandan78 Mar 07 '17 at 21:28
  • Check for boost multiprecision. There are also other implementation. – overseas Mar 07 '17 at 21:28
  • 2
    Oh and a little note about style: Why cast the integer in your example? Why not simply have e.g. `22.0 / 7.0`? – Some programmer dude Mar 07 '17 at 21:28
  • Does this mean that I cannot get the correct answer without adding other libraries on it? I am using code blocks. –  Mar 07 '17 at 21:36
  • 1
    Check out [GMP](https://gmplib.org/). – Jesper Juhl Mar 07 '17 at 21:37
  • @JesperJuhl For floats, better use MPFR (which itself uses GMP and used to be part of GMP) instead of GMP. – Marc Glisse Mar 07 '17 at 21:39
  • 1
    "Does this mean that I cannot get the correct answer without adding other libraries on it?" Unfortunately this is true. The standard floating point types are incapable of correct representation after a point. They run out of bits. Give this a read for more information: https://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html – user4581301 Mar 07 '17 at 21:45

1 Answers1

5

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.

Caleb
  • 124,013
  • 19
  • 183
  • 272
Slava
  • 43,454
  • 1
  • 47
  • 90