/// <summary> /// Pick an array element with probability proportional to exp(-cost). /// </summary> public static int sample_by_costs(Floatarray costs) { Doublearray p = new Doublearray(); p.Copy(costs); double mincost = NarrayUtil.Min(costs); p -= mincost; for (int i = 0; i < p.Length(); i++) { p.UnsafePut1d(i, Math.Exp(-p.UnsafeAt1d(i))); } double sump = NarrayUtil.Sum(p); p /= sump; double choice = rnd.NextDouble(); double s = 0; for (int i = 0; i < p.Length(); i++) { s += p[i]; if (choice < s) { return(i); } } // shouldn't happen... return(costs.Length() - 1); }
/// <summary> /// Pick an array element with probability proportional to exp(-cost). /// </summary> public static int sample_by_costs(Floatarray costs) { Doublearray p = new Doublearray(); p.Copy(costs); double mincost = NarrayUtil.Min(costs); p -= mincost; for (int i = 0; i < p.Length(); i++) p.UnsafePut1d(i, Math.Exp(-p.UnsafeAt1d(i))); double sump = NarrayUtil.Sum(p); p /= sump; double choice = rnd.NextDouble(); double s = 0; for (int i = 0; i < p.Length(); i++) { s += p[i]; if (choice < s) return i; } // shouldn't happen... return costs.Length() - 1; }