Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to raise the precision of pow in C++ for large numbers (10^19)?

I am looking to calculate 9^19. my code is:

    cout.setf(ios::fixed, ios::floatfield);
    cout.setf(ios::showpoint);
    cout<<pow(9,19)<<endl;

The result has the last 2 digits equal to 0: 1350851717672992000. In Python,9**19 got me 1350851717672992089L . Seems a floating point issue. How could I raise the precision for pow? or how to preform a better precision power than pow?

I am compiling with gcc version 4.8.2.

like image 505
Assem Avatar asked Dec 24 '22 19:12

Assem


1 Answers

It is indeed a floating-point issue: a typical 64-bit double only gives 53 bits, or about 15 decimal digits, of precision.

You might (or might not) get more precision from long double. Or, for integers up to about 1019, you could use uint64_t. Otherwise, there's no standard type with more precision: you'll need a library such as GMP or Boost.Multiprecision.

like image 85
Mike Seymour Avatar answered Feb 21 '23 00:02

Mike Seymour