4. Evaluate probabilities¶
A lawn is wet when it rains or the sprinkler runs: W = R ∨ S. Assume independent rain, sprinkler and wind variables. Wind does not affect wetness, but belongs to the model’s universe.
4.1. Build events¶
Build the wet event and the joint event R ∧ W.
enum { RAIN = 1, SPRINKLER, WIND };
const int64_t causes[] = {RAIN, SPRINKLER};
TididiCircuit *wet = NULL, *rain = NULL, *rain_and_wet = NULL;
check(tididi_clause(vtree, causes, 2, &wet, NULL));
check(tididi_literal(vtree, RAIN, &rain, NULL));
TididiCircuit *wet_copy = copy(wet);
check(tididi_and(rain, wet_copy, &rain_and_wet, NULL));
4.2. Assign probabilities¶
For each variable, give the probabilities of false and true as exact fraction strings. The weighted sum is the probability of the event. Conditional probability divides the joint event’s mass by the evidence’s mass: P(R | W) = P(R ∧ W) / P(W). Here the evidence has positive probability. The returned strings preserve exact arithmetic without a separate C rational type.
TididiWeight weights[] = {
{RAIN, "4/5", "1/5"}, {SPRINKLER, "9/10", "1/10"}, {WIND, "3/5", "2/5"}
};
char *mass = NULL, *conditional = NULL;
check(tididi_weighted_count(wet, weights, 3, &mass, NULL));
check(tididi_weighted_ratio(rain_and_wet, wet, weights, 3, &conditional, NULL));
printf("P(wet) = %s\nP(rain | wet) = %s\n", mass, conditional);
tididi_string_free(mass); tididi_string_free(conditional);
Output:
P(wet) = 7/25
P(rain | wet) = 5/7
4.3. Change a prior¶
Changing weights does not require rebuilding either event.
weights[0].negative = "2/5";
weights[0].positive = "3/5";
mass = NULL; conditional = NULL;
check(tididi_weighted_count(wet, weights, 3, &mass, NULL));
check(tididi_weighted_ratio(rain_and_wet, wet, weights, 3, &conditional, NULL));
printf("P(wet) = %s\nP(rain | wet) = %s\n", mass, conditional);
tididi_string_free(mass); tididi_string_free(conditional);
Output:
P(wet) = 16/25
P(rain | wet) = 15/16
4.4. Change observations¶
An evaluator consumes its circuit and retains values for repeated evidence
updates. With no rain observed, its value is the joint probability P(W ∧ ¬R).
Clearing observations restores the unobserved value; tididi_evaluator_finish
returns the original circuit.
TididiEvaluator *evaluator = NULL;
check(tididi_evaluator(wet, weights, 3, &evaluator));
const int64_t no_rain[] = {-RAIN};
check(tididi_evaluator_observe(evaluator, no_rain, 1));
mass = NULL;
check(tididi_evaluator_value(evaluator, &mass, NULL));
printf("P(wet and no rain) = %s\n", mass);
tididi_string_free(mass);
check(tididi_evaluator_clear_all(evaluator));
mass = NULL;
check(tididi_evaluator_value(evaluator, &mass, NULL));
printf("P(wet) = %s\n", mass);
tididi_string_free(mass);
Output:
P(wet and no rain) = 1/25
P(wet) = 16/25
4.5. Complete program¶
Download probability.c and the
shared helper. The source includes cleanup
for all handles. Both files are included in the source checkout.