📜  C++ 17中的std :: legendre,std :: legendref和std :: legendrel函数

📅  最后修改于: 2021-05-30 03:10:21             🧑  作者: Mango

legendre,legendref和legendrel是C++ STL中的内置函数,用于计算度数n和参数x的未关联多项式的值。 x的n阶未关联勒让德多项式的值由下式给出:

      \[         \ P_{n}(x)= \frac{1}{2^{n}n!}\frac{d^{n}}{dx^{n}}(x^{2}-1)^{n}      \]

勒让德多项式的前几个是

      \[      Legendre(0,x)= 1 \]  \[      Legendre(1,x)= x \]  \[      Legendre(2,x)= \frac{1}{2} ( 3x^{2}-1 ) \] \[      Legendre(3,x)= \frac{1}{2} ( 5x^{3}-3x ) \]

句法:

double legendre( unsigned int n, double x )
             or 
double legendre( unsigned int n, float x )
             or 
double legendre( unsigned int n, long double x )
             or
float legendref( unsigned int n, float x )
             or
long double legendrel( unsigned int n, long double x )

参数:该函数接受两个强制性参数,如下所述:

  • n:指定多项式的次数。
  • x:指定参数,该参数表示浮点或整数类型的值

返回值:该函数返回参数x的n阶不相关的勒让德多项式的值。返回类型取决于传递的参数。

注意:该函数在C++ 17(7.1)及更高版本中运行。

下面的程序说明了上述功能:

// C++ program to illustrate the above 
// mentioned three functions
#include  
#include 
using namespace std;
int main()
{
    // int and double as parameter 
    cout << "legendre(2,0.3)= " << legendre(2,0.3);
      
    //  x as double type parameter
    cout << "\nlegendre(3,(double)0.4)=" << legendre(3,(double)0.4);
      
     // x as float 
     cout << "\nlegendre(3,(float)0.4)= " << legendre(3,(float)0.4);
  
    //  legendref 
    cout << "\nlegendref(3, 0.45)= " << legendref(3, 0.45);
  
    // legendrel
    cout << "\nlegendrel(7, 0.50)= " << legendrel(7, 0.50);
      
    return 0;
}

错误和异常:该函数在以下三种情况下引发错误:

  • 如果参数为NaN,则返回NaN并且不报告域错误
  • | x |> 1不需要定义该函数
  • 如果n大于或等于128,则行为是实现定义的

下面的程序说明了以上错误:

程序1:

// C++ program to illustrate the above 
// mentioned three functions
// domain error
#include  
#include 
using namespace std;
int main()
{
    // int and double as parameter 
    cout << "legendre(129, 2)= " << legendre(129, 2);
          
    return 0;
}

输出:

terminate called after throwing an instance of 'std::domain_error'
  what():  Argument out of range in __poly_legendre_p.
legendre(129, 2)=

程式2:

// C++ program to illustrate the above 
// mentioned three functions
// when x is NaN
#include  
#include 
using namespace std;
int main()
{
    // int and double as parameter 
    cout << "legendre(129, NaN)= " << legendre(129, sqrt(-2));
      
    return 0;
}

输出:

legendre(129, NaN)= nan

程序3:

// C++ program to illustrate the above 
// mentioned three functions
// domain error
#include  
#include 
using namespace std;
int main()
{
    // int and double as parameter 
    cout << "legendre(129, 2)= " << legendre(129, 2);
      
    return 0;
}

输出:

terminate called after throwing an instance of 'std::domain_error'
  what():  Argument out of range in __poly_legendre_p.
要从最佳影片策划和实践问题去学习,检查了C++基础课程为基础,以先进的C++和C++ STL课程基础加上STL。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程”