为什么这个函数返回不同的值?

时间:2015-10-07 15:31:02

标签: c++ function complex-numbers complextype

我用C ++编写了一个函数来计算球面谐波(使用gcc复杂库):

#include <iostream>
#include <cmath>
#include <complex>
using namespace std;

double plegendre( int, int, double );

complex<double> SphericalHarmonicY( int l, int m, double theta, double phi )
{
   int m_abs;
   double im, re, plm;
   complex<double> output;

   m_abs = fabs(m);

   plm = plegendre( l, m_abs, cos( theta ) );

   re = plm * cos( m * phi );
   im = plm * sin( m * phi );

   if ( m < 0 )
   {
     re = - re;
     im = - im;
   }

   output = complex<double>( re, im );

   cout << " {" << l << "," << m << "}\t" << "theta = " << theta << " phi = " << phi << 
   " SH = " << output << endl;

   return output;
}

如果我通过一个简单的“main()”来调用这个函数,它就会工作并给出正确的值。

但是,当通过下面的子程序调用时,它只给出m的值的正确实部,这些m是奇数的m值的偶数和正确的虚部。谁能解释一下呢?

#include <iostream>
#include <cmath>
#include <complex>
#include "MyHeader.h"

void SphericalHarmCalc( int* P, double* theta, double* phi, SpherHarm** &SHout )
{
   int l, m, i{0};
   double theta_, phi_;

   theta_ = *theta;
   phi_   = *phi;

   SHout = new SpherHarm*[(*P)+1];

   for ( i = 0; i <= (*P); i++ )
   {    
      SHout[i] = new SpherHarm[(2*i)+1];
   }

   for ( l = 0; l <= (*P); l++)
   {
      i = 0;
      for ( m = -l; m <= l; m++ )
      {
         SHout[l][i].lm[0] = l;
         SHout[l][i].lm[1] = m;

         SHout[l][i].val = SphericalHarmonicY( l, m, theta_, phi_ );
         i++;
      }
      cout << endl << endl;
   }
}

这让我困惑了一段时间。

(我也会使用delete[]稍后释放堆 - 在此子例程之外)。

SpherHarm类在MyHeader.h中定义:

class SpherHarm
{
   public:
     int* lm = new int[2];
     complex<double> val;
};

我正在使用带有标志的g ++编译器(版本4.8.2):

g++ -Wall -std=c++11

提前致谢!

0 个答案:

没有答案