Long double overflows but value smaller than maximum representable value

给你一囗甜甜゛ 提交于 2021-02-11 09:18:31

问题


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?


回答1:


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



来源:https://stackoverflow.com/questions/42908181/long-double-overflows-but-value-smaller-than-maximum-representable-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!