C ++ Theta函数实现

时间:2016-06-22 10:59:33

标签: c++

我正在尝试实现此功能:

  

formula

但它没有用。最小的,可验证的示例如下:

#include <iostream>
#include <cmath>

int main()
{
  int N {8};        // change this for testing <1..inf>
  double q {0.1 / N};
  int countN {static_cast<int>(floor(N / 2))};
  static const double PI {3.1415926535897932384626433832795};

  // Omega[i] =  Theta1(u,m) / Theta4(u,m)
  double Omega[countN];
  for (int i=0; i<countN; ++i)
  {
    double micro {!(N % 2) * 0.5};  // 0 for odd N, 1/2 for even N
    double num[countN] {sin(PI / N * (i + 1 - micro))};
    double den[countN] {0.5};

    for (int m=1; m<4; ++m)
    {
        num[i] += pow(-1, m) * pow(q, m*(m + 1)) * sin((2 * m + 1) * PI / N * (i + 1 - micro));
        den[i] += pow(-1, m) * pow(q, m*m) * cos(2 * m * PI / N * (i + 1 - micro));

    }
    Omega[i] = fabs(pow(q, 0.25) * num[i] / den[i]);
    std::cout << "  " << Omega[i] << "\n";
  }

  // testing the values, they should be increasing in value
  for (const auto &elem: Omega)
    std::cout << elem << " ";
  std::cout << "\n";

  return 0;
}

与原始版本相比有一个小的简化:我在分子和分母中考虑了2,我只使用了分数之外的q^0.25。此外,countN是原始文档中的rmicro只是偶数1/2的{​​{1}}或{{1} N对于数组的索引,0为0,但计算时为N,但这些并不重要。

我用wxMaxima尝试了这个:

i

结果,用C ++:

i+1

和wxMaxima:

Theta[1](x,y):=2*y^0.25*sum( (-1)^k*y^(k*(k+1))*sin((2*k+1)*x),k,0,n );
Theta[4](x,y):=1+2*sum( (-1)^k*y^(k^2)*cos(2*k*x),k,1,n );
n:4$
N:8$
a:0.05$
b(i):=%pi/N*(i-(1-mod(N,2))/2)$
for N:8 thru 9 do for i:1 thru N/2 do print(["N=",N,"i=",i],Theta[1](b(i),a)/Theta[4](b(i),a)),numer;

令我惊讶的是,对于bith (q=0.05; N=8) Omega[0]=0.2018370065366672 Omega[1]=0.06058232646142273 Omega[2]=0.01205653570636574 Omega[3]=0.02127667733703158 (q=0.05; N=9) Omega[0]=0.348078726440638 Omega[1]=0.1178366281313341 Omega[2]=2.559808325080287e-07 Omega[3]=0.02178788541277828 ,第一个词是好的,所以我不能告诉我的代码中哪些不对。有人可以帮我发现错误吗?

要明确一点:我是C ++的初学者,我不是在找人为我做,而是让我知道编码中的错误(将数学翻译成C ++代码)。

1 个答案:

答案 0 :(得分:1)

你有

var entry = [{ candidate: "guy1", rank: 1, state: "AK", vote_count: "2" }, { candidate: "guy2", rank: 1, state: "MI", vote_count: "3" }, { candidate: "guy3", rank: 1, state: "AK", vote_count: "5" }, { candidate: "guy2", rank: 1, state: "AL", vote_count: "4" }, { candidate: "guy2", rank: 1, state: "FL", vote_count: "9" }, { candidate: "guy1", rank: 1, state: "MN", vote_count: "7" }],
    count = {};

entry.forEach(function (a) {
    count[a.candidate] = (count[a.candidate] || 0) + +a.vote_count;
});

console.log(count);

这会将double den[countN] {0.5}; 的第一个元素初始化为den ,将所有其他元素初始化为0.5 (默认初始化)。换句话说,以上等同于

0.0

填充数组需要尽可能多的零。您可能希望将所有元素初始化为double den[countN] {0.5, 0.0, 0.0, 0.0}; 。在您的情况下,最简单的方法是首次使用该元素时 - 或者,因为您在0.5的生命周期内仅访问单个元素den[i],所以将其设为普通{{1}而不是数组:

den