Search code examples
cprecisionnumerical-methodspow

Increase precision up to 20 decimal places for a function like pow() in C


I am working with gcc 4.9.2 in Debian 8 over a Thinkpad T430.

A part of my code uses the following function:

long double LF_NormalizationFactor(int total_number_of_nodes,double alpha)
{
    long double sum;
    int maximum_distance;

    if( (total_number_of_nodes % 2) == 0 )
    {

        maximum_distance = total_number_of_nodes/2;
        sum = 2/pow(maximum_distance,alpha);
        maximum_distance = maximum_distance - 1;
        while( maximum_distance != 0)
        {
             sum = sum + 2/pow(maximum_distance,alpha);
             maximum_distance = maximum_distance - 1;
        }

     }
    else
    {
         maximum_distance = total_number_of_nodes/2;
         sum = 2/pow(maximum_distance,alpha);
         maximum_distance = maximum_distance - 1;
         while( maximum_distance != 0)
         {
             sum = sum + 2/pow(maximum_distance,alpha);
             maximum_distance = maximum_distance - 1;
         }  
    }

    return sum;
}

Which returns a value calculated with the function pow().

The problem is that I need to increase the precision up to 20 decimal places because, in short, I have to calculate variations for 10^-19.

The thing is that, after some research here and google, I came to the conclusion that pow(), as is, gives only up to 15 decimal places.

Example:

total_number_of_nodes = 40 alpha = 1.50

return: 2.000000000000001776

(and I need 2.000000000000000000)

Any suggestion?

Thanks


Solution

  • You're conclusion is correct, pow() is a double precision function, not a long double (extended) precision function. There should be a long double version for pow, usually it's powl() . That should give you 19 digits with a bit of margin log10(2^64) ~= 19.266.

    Example runs using powl:
    
    total_number_of_nodes =  2 alpha = 1.50
    return: 2.000000000000000000
    
    total_number_of_nodes = 40 alpha = 1.50
    return: 4.341364142887200054
    

    Why is the example code from the question identical for total_number_of_nodes even or odd?