How to extend the precision of mpreal precisely?

449 views Asked by At

Consider the following code:

#include <iostream>
#include <mpreal.h>
using namespace std;
using mpfr::mpreal;

mpreal x("1.001",64);
mpreal y("1.0",64);
y*=x;
cout<<y<<endl;  //1
y.set_prec(128);
cout<<y<<endl;  //2

The outputs are

1.001

1.00100000000000000002081668171172168513

I wish that the second output is something like

1.00100000000000000000000000000000000000

In fact, I've learned that one can replace

y.set_prec(128);

to

y=mpreal(y.toString(),128);

But this kind of conversion is time consuming.

Is there any better/faster method?

Thanks!

1

There are 1 answers

1
Pavel Holoborodko On BEST ANSWER

It is better to setup precision globally, so that all mpreal variables will be created with such precision by default. Call the following function before creating any mpreal numbers:

mpfr::mpreal::set_default_prec(mpfr::digits2bits(N));

mpreal x("1.001");  // second argument is not required anymore
mpreal y("1.0");
...

where N is required precision in decimal digits.

Binary floating-point numbers don't give you actual decimal precision, it is only approximations to real numbers. More bits in representation = higher approximation accuracy. But some numbers can never be represented exactly in binary format. The 1.001 is one of them. So that you will always see non-zeros starting from some position in binary representation of 1.001 number.

Check What Every Computer Scientist Should Know About Floating Point Arithmetic for more details.