|
|
|
Appendix III – Code Samples
The following code fragments show how to implement these algorithms in languages like C. A slightly more general terminology has been used, for example the keyword "global" is introduced since in C the scope of a variable is defined by its position and this creates confusion when looking at code fragments. I have also replaced the specialised keywords "float" and "double" with "real". The first code fragment shows how to convert a numerical Score between 0 and 1 to a traffic light representation: /* Red, Yellow, Green and Score are reals */global real Red, Yellow, Green; /* convert Score to one or two traffic lights */ real indicate(real Score) { /* check that Score is in valid range */ if (Score < 0 || Score > 1) return(-1); if (Score < 0.5) { Yellow = 2*Score; Red = 1 – Yellow; Green = 0; } else { Yellow = 2 - 2*Score; Green = 1 – Yellow; Red = 0; } return(Score); } The next code fragment shows how to integrate a set of N weighted Indicators or Characteristics. The individual memberships are stored in the arrays R[idx], Y[idx] and G[idx], and the weights are W[idx], where idx is an index that runs from 1 to N, and the integrated values are stored in R[0], Y[0] and G[0] (W[0] is used for the sum of weights, and should be 1 if the weights are normalised). The arrays are statically dimensioned to the largest value of N, Nmax, that is used. global real R[Nmax], Y[Nmax], G[Nmax], W[Nmax];/* combine and integrate indicator values */ void integrate (int N) { /* initialise variables */ R[0] = 0; Y[0] = 0; G[0] = 0; W[0] = 0; int idx = 0; /* run a loop from 1 to N */ while (idx++ < N) { /* increment the storage counters */ R[0] += W[idx] * R[idx]; Y[0] += W[idx] * Y[idx]; G[0] += W[idx] * G[idx]; W[0] += W[idx]; } /* divide the weighted sums by total weight */ R[0] /= W[0]; Y[0] /= W[0]; G[0] /= W[0]; return; } The final code fragments do defuzzification: /* convert traffic lights to numeric score */real defuzzify(real Red, Yellow, Green) { return(0.5 * Yellow + Green); } /* calculate uncertainty in traffic lights */ real discord(real Red, Yellow, Green) { return(4.0 * Red * Green); } |
|
All material on this site copyright 2002-2005 by William Silvert unless otherwise indicated. This page was last updated on 10 November 2005 . |