简体   繁体   中英

Long double overflows but value smaller than maximum representable value

I'm trying to compute a series using C++. The series is:
系列 (for those wondering)

My code is the following:

#include <iostream>
#include <fstream>
#include <cmath> // exp 
#include <iomanip> //setprecision, setw 
#include <limits> //numeric_limits (http://en.cppreference.com/w/cpp/types/numeric_limits)

long double SminOneCenter(long double gamma)
{
    using std::endl; using std::cout;
    long double result=0.0l;
    for (long double k = 1; k < 1000 ; k++)
    {   
            if(isinf(pow(1.0l+pow(gamma,k),6.0l/4.0l)))
            {   
                    cout << "infinity for reached for gamma equals:   " << gamma <<  "value of k:  " << k ; 
                    cout << "maximum allowed:   " <<  std::numeric_limits<long double>::max()<< endl;
                    break;
            }   

                    // CAS PAIR: -1^n = 1
                    if ((int)k%2 == 0)
                    {   
                            result += pow(4.0l*pow(gamma,k),3.0l/4.0l) /(pow(1+pow(gamma,k)),6.0l/4.0l);
                    }   
                    // CAS IMPAIR:-1^n = -1
                    else if ((int)k%2!=0)
                    {   
                            result -= pow(4.0l*pow(gamma,k),3.0l/4.0l) /(pow(1+pow(gamma,k)),6.0l/4.0l);

                            //if (!isinf(pow(k,2.0l)*zeta/2.0l))
                    }   
                    //              cout << result << endl;
    }    


    return 1.0l + 2.0l*result;
}

Output will be, for instance with gamma = 1.7 : infinity reached for gamma equals: 1.7 value of k : 892

The maximum value a long double can represent, as provided by the STL numeric_limits , is: 1.18973e+4932 .

However (1+1.7^892)= 2.19.... × 10^308 which is way lower than 10^4932 , so it shouldn't be considered as infinity.

Provided my code is not wrong (but it very well might be), could anyone tell me why the discussed code evals to infinity when it should not?

You need to use powl rather than pow if you want to supply long double arguments.

Currently you are hitting the numeric_limits<double>::max() in your pow calls.

As an alternative, consider using std::pow which has appropriate overloads.

Reference http://en.cppreference.com/w/c/numeric/math/pow

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM