Convolution of dice

I have a biased dice with probability of throwing 1,2,3,4,5,6 as 0.35 , 0.10, 0.05, 0.05, 0.15, 0.30 respectively. now I want to calculate the expected value of the sum of thrown values, if i throw 10 such dice. I wrote a code in python it worked perfectly and now i have to translate it to c++ and am still new to c++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
  #include<bits/stdc++.h>
#include<algorithm>
using namespace std;
vector<float> convolution (vector<float> prob1, vector<float> prob2)
{
    int n = prob1.size();
    int m = prob2.size();
    vector<float> Sum((n+m-1), 0.);
    for(int i=0; i<n; i++){
        for(int j=0;j <m;j++){
            Sum[i+j]= prob1[i]*prob2[j];
        }
    }
    return Sum;
}
vector<float> recursive (int n){
    vector<float> prob1={0.35,0.10, 0.05, 0.05,0.15,0.30};
    vector<float> prob2={0.35,0.10, 0.05, 0.05,0.15,0.30};
    vector<float> a= convolution(prob1,prob2);
    vector<vector<float>> TOTAL ={a};
    if (n==1){
        return prob1;
    }
    else{
        for(int i =2; i<n;i++){
            vector<float> r =convolution(TOTAL[i-2], prob1);
            TOTAL.push_back(r);
        }
        vector<float> a= TOTAL[-1];
        return a;
    }
}
int main(){
   vector<float> R= recursive(10);
    float a;
    vector<float> ExpectedValue;
    for(int i=0; i< R.size();i++){
        ExpectedValue.push_back(R[i]*(i+10));
        a +=R[i]*(i+10);
    }
    cout<<a<<endl;

}
1
2
3
4
5
for(int i=0; i<n; i++){
  for(int j=0;j <m;j++){
    Sum[i+j]= prob1[i]*prob2[j];
  }
}

I see n*m assignments in that loop, yet you assign to only n+m-1 elements. In other words, you would get the same result with n+m-1 assignments. Not an error though.


There are two obvious points of error:

Line 29: TOTAL[-1]
Q: Which element is at index -1?
A: -1 is not a valid index to vector.
http://www.cplusplus.com/reference/vector/vector/operator[]/
Portable programs should never call this function with an argument n that is out of range, since this causes undefined behavior.


Line 39:
1
2
float a; // uninitialized
a +=R[i]*(i+10); // unknown + something is still unknown 
Registered users can post here. Sign in or register to post.