A Civilization-style strategy game about governing Israel from 15 May 1948. Real ministers, real map, every fact sourced. Unity + deterministic C# sim.
Sim: sum each voter group's weights in ordinal key order (Refs #2511) (#2550)
Beriebeb223d633a
diff --git a/changelog.d/2511-approval-ordinal-sum.md b/changelog.d/2511-approval-ordinal-sum.mdnew file mode 100644index 000000000..f4db7cbad--- /dev/null+++ b/changelog.d/2511-approval-ordinal-sum.md@@ -0,0 +1,4 @@+### Changed++- Approval (Refs #2511): each voter group's weights are now summed in a fixed (ordinal key) order, so the result no+ longer rests on the order a dictionary happens to return them in. Shipped content gives the same numbers as before.diff --git a/sim/Statecraft.Sim.Tests/DeterminismTests.cs b/sim/Statecraft.Sim.Tests/DeterminismTests.csindex 864235b57..834b95f3c 100644--- a/sim/Statecraft.Sim.Tests/DeterminismTests.cs+++ b/sim/Statecraft.Sim.Tests/DeterminismTests.cs@@ -69,4 +69,21 @@ public class DeterminismTestsAssert.Equal(GoldenRun.Hash1950, GoldenHash);Assert.Equal(GoldenRun.Hash1952, GoldenHash1952);}++ // #2511: a floating-point sum over a Dictionary follows its enumeration order, which .NET does not promise. 0.1, 0.2+ // and 0.3 add to a different last bit in the two orders, so this fails unless the sum fixes the order (ordinal keys).++ [Fact]+ public void ApprovalDoesNotDependOnTheWeightsInsertionOrder()+ {+ var c = ContentLoader.Load(Fixture.Write());+ var s = new GameState { Date = new DateTime(1948, 6, 1) };+ EffectsSystem.Init(c, s);+ s.Indicators["food_supply"] = s.Indicators["housing"] = s.Indicators["morale"] = 1.0;+ var group = c.At(s.Date).VoterGroups[0];+ group.Weights = new Dictionary<string, double> { ["food_supply"] = 0.1, ["housing"] = 0.2, ["morale"] = 0.3 };+ var forward = EffectsSystem.Approval(c, s);+ group.Weights = new Dictionary<string, double> { ["morale"] = 0.3, ["housing"] = 0.2, ["food_supply"] = 0.1 };+ Assert.Equal(forward, EffectsSystem.Approval(c, s));+ }}diff --git a/sim/Statecraft.Sim/EffectsSystem.cs b/sim/Statecraft.Sim/EffectsSystem.csindex 671887f68..2119d5675 100644--- a/sim/Statecraft.Sim/EffectsSystem.cs+++ b/sim/Statecraft.Sim/EffectsSystem.cs@@ -167,8 +167,9 @@ namespace Statecraft.Sim}}+ // The weights are summed in ordinal key order: a floating-point sum depends on its order, and a Dictionary's is not promised (#2511).public static double Approval(Content c, GameState s) =>c.At(s.Date).VoterGroups.Count == 0 ? 0.5 :- c.At(s.Date).VoterGroups.Average(g => Math.Max(0, Math.Min(1, g.Weights.Sum(w => w.Value * s.Indicators[w.Key]))));+ c.At(s.Date).VoterGroups.Average(g => Math.Max(0, Math.Min(1, g.Weights.OrderBy(w => w.Key, StringComparer.Ordinal).Sum(w => w.Value * s.Indicators[w.Key]))));}}