Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loss of precision when using pow in C++

Tags:

c++

precision

pow

10^1.64605 = 44.2639330165

However in C++ using pow:

double p = pow(10,1.64605) returns 44.2641. 

Is there a way to increase the precision here? I tried casting both sides to long double but that didn't help either.

More interesting is:

cout<<p;
double a = -1.64605;
cout<<pow(10,-a);
p = pow(10, (-p));
cout<<p;

the output is:

-1.64605
44.2639
44.2641

Why?

like image 694
user3639557 Avatar asked Apr 22 '15 03:04

user3639557


1 Answers

cout is truncating your double for display, but the value calculated by pow is probably at least as precise as you expect. For how to get more precision displayed in the console see:

How do I print a double value with full precision using cout?

I'll elaborate given the prodding by David.

You stated that double p = pow(10,1.64605) returns 44.2641 but this is incorrect. It returns 44.26393301653639156; without any formatting specifiers this displays as 44.2639 (as you see later).

When you cout the original value of p in the second code snippit it displays -1.64605 (due to reduced precision formatting) and you are assuming that it is exactly -1.64605 whereas it is actually somewhere between -1.64605115... and -1.64605213..., which does evaluate to 44.2641 in the expression cout << pow(10, (-p));

like image 175
Qartar Avatar answered Oct 01 '22 12:10

Qartar