0

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.

Scott
  • 113
  • 4

1 Answers1

0

Given that your current code could cause evaluation of sub-expressions that fall outside of the finite range of representable values for double, I'd recommend rewriting the expression. Consider something like this:

P(k) = [ea*F(k)]/[Σi=1,...,Nea * F(i)]

P-1(k) = [Σi=1,...,Nea * F(i)] / [ea*F(k)]

P-1(k) = Σi=1,...,N[ea * F(i) / ea*F(k)]

P-1(k) = Σi=1,...,N[ea * F(i) - a * F(k)]

P-1(k) = Σi=1,...,N[ea * (F(i) - F(k))]

P(k) = [Σi=1,...,N[ea * (F(i) - F(k))]]-1

If you could provide a minimal, complete and testable example, you could probably get considerably better advice.

EOF
  • 6,273
  • 2
  • 26
  • 50