简体   繁体   中英

From mathematic function to c++ code

I am trying to implement this F(S) function:

在此输入图像描述

bellow is my code but is not working:

double EnergyFunction::evaluate(vector<short> field) {
    double e = 0.0;
    for (int k = 1; k < field.size() - 1; k++){
        double c = 0.0;
        for (int i = 1; i < field.size() - k; i++) {
            c += field[i] * field[i + k];
        }
        e += pow(c, 2);
    }
    double f = pow(field.size(), 2) / ( 2 * e );
    return f;
}

For example F(S) function should return value 8644 for vector:

1,1,1,-1,-1,-1,1,-1,1,1,-1,1,-1,1,-1,1,-1,-1,1,1,1,1,-1,-1,-1,1,1,1,1,-1,1,-1,1,1,-1,-1,1,1,1,1,-1,-1,-1,1,-1,-1,1,-1,-1,1,1,-1,1,-1,-1,1,1,-1,1,-1,1,-1,1,-1,1,-1,1,1,-1,-1,-1,-1,-1,-1,1,-1,1,1,1,-1,1,1,-1,1,1,-1,1,-1,1,1,1,-1,-1,1,1,-1,-1,1,1,1,1,1,1,1,1,-1,1,-1,1,-1,1,-1,-1,1,-1,-1,1,-1,-1,1,-1,-1,-1,-1,-1,1,1,1,1,1,-1,-1,-1,1,-1,-1,1,-1,-1,1,-1,-1,1,-1,1,-1,-1,1,1,1,1,1,1,-1,1,-1,1,-1,1,1,1,1,1,1,-1,1,-1,-1,-1,1,-1,1,1,-1,-1,-1,-1,1,-1,-1,-1,1,1,-1,-1,1,1,1,-1,-1,1,1,1,1,-1,1,1,-1,1,-1,-1,1,-1,-1,-1,-1,1,-1,-1,-1,1,-1,-1,1,1,-1,-1,-1,-1,-1,1,-1,-1,-1,1,1,-1,1,1,-1,-1,-1,1,-1,-1,1,-1,-1,-1,1,1,1,-1,-1,-1,-1,1,1,1,-1,1,-1,-1,1,-1,1,1,-1,-1,-1,-1,1,-1,1,1,1,1,1,1,-1,1,1,1,-1,-1,-1,-1,1,-1,1,1,1,1,-1,1,1,1,1,1,-1,-1,-1,1,-1,-1,1,1,1,-1,1,1,1,-1,1,1   

I need another par of eyes to look at my code because I am a bit lost here. :)

You are mapping variables into different ranges using the same names, which is always going to be confusing. Better is to keep ranges and names the same as in the math, and only subtract one for 0-base indexes at indexing time. Also might as well use L explicitly:

int L = field.size();
for (int k = 1; k <= L-1; k++){
    ...
    for (int i = 1; i <= L-k; i++) {
        c += field[i -1] * field[i+k -1];
    ...

after refactoring:

double EnergyFunction::evaluate(vector<short> field) {
  double e = 0.0;
  int l = field.size()
  for (int k = 1; k < l; k++){
    double c = 0.0;
    for (int i = 0, j = k; j < l; i++, j++) {
        c += field[i] * field[j];
    }
    e += c*c;
  }
  return l*l / ( e+e );
}

explanation:
1. we need to iterate (L-1) times
2. we need to shift the base and offset indexes until we reach the last one
3. c*c and e+e are quicker and easier to read

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