I am relatively new to C and so when it comes to issues of precision I am always a bit worried. I am working with a rather larger code and at a specific point I need to select a value based off of a discrete probability distribution. Essentially what I need to do is select a value k=1,2,...N with probabilities given by the formula
P(k) = [ea*F(k)]/[Σi=1,...,NeaF(i)],
where F is just some function that uses k as an input and a is a real number. [Sorry the formula looks rough I wasn't sure how to format it.] My code looks (roughly) like this so far. I've had to make some changes to aid readability out of context.
int k;
int N=10;
double a=5.5; //In the code it is just a positive real number
double xtemp=0;
double X[10];
double fk;
for(k=0;k<N;k++){
fk = F(k); // Here F returns a double
xtemp += exp(a*fk);
X[k]=xtemp;
}
xtemp = xtemp*U01(); //U01 returns a uniformly random number on [0,1]
for(k=0;k<K;k++){
if(xtemp<=X[k]){
return k;
}
}
This should give the desired result from a mathematical perspective, however someone better at coding than me said the xtemp could become problematic and become imprecise. I was wondering how you could do error handling for this? I'd also be open to a better way to implement the idea. I appreciate any help and advice.