{"record":{"id":"353a8f8c6fceec2a","repo":"rohitg00/ai-engineering-from-scratch","slug":"gamma-shape-parameter-must-be-positive","errorCode":null,"errorMessage":"Gamma shape parameter must be positive","messagePattern":"Gamma shape parameter must be positive","errorType":"validation","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"phases/01-math-foundations/07-bayes-theorem/code/bayes.py","lineNumber":320,"sourceCode":"    lifts.sort()\n    median_lift = lifts[len(lifts) // 2]\n    low = lifts[int(len(lifts) * 0.05)]\n    high = lifts[int(len(lifts) * 0.95)]\n    print(f\"  Median lift: {median_lift:.1%}\")\n    print(f\"  90% credible interval: [{low:.1%}, {high:.1%}]\")\n\n\ndef _beta_sample(alpha, beta_param, rng_module):\n    x = _gamma_sample(alpha, rng_module)\n    y = _gamma_sample(beta_param, rng_module)\n    if x + y == 0:\n        return 0.5\n    return x / (x + y)\n\n\ndef _gamma_sample(shape, rng_module):\n    if shape <= 0:\n        raise ValueError(\"Gamma shape parameter must be positive\")\n    if shape < 1:\n        return _gamma_sample(shape + 1, rng_module) * rng_module.random() ** (1.0 / shape)\n\n    d = shape - 1.0 / 3.0\n    c = 1.0 / (9.0 * d) ** 0.5\n\n    while True:\n        x = rng_module.gauss(0, 1)\n        v = (1 + c * x) ** 3\n        if v <= 0:\n            continue\n        u = rng_module.random()\n        if u < 1 - 0.0331 * x ** 4:\n            return d * v\n        if math.log(u) < 0.5 * x ** 2 + d * (1 - v + math.log(v)):\n            return d * v\n\n","sourceCodeStart":302,"sourceCodeEnd":338,"githubUrl":"https://github.com/rohitg00/ai-engineering-from-scratch/blob/39ea8a1c6d0b61f071226eff7ede4d4105fed820/phases/01-math-foundations/07-bayes-theorem/code/bayes.py#L302-L338","documentation":"Raised in _gamma_sample when the shape parameter is zero or negative. Gamma sampling (used by _beta_sample for posterior draws) is only defined for a positive shape, and the Marsaglia-Tsang-style algorithm branches on shape >= 1, so non-positive input is rejected up front.","triggerScenarios":"Thrown at phases/01-math-foundations/07-bayes-theorem/code/bayes.py:320 when the library encounters an invalid state.","commonSituations":"See trigger scenarios.","solutions":["Pass positive alpha/beta parameters to _beta_sample (they propagate to _gamma_sample)","Validate posterior parameters before sampling: Beta(alpha, beta) requires alpha > 0 and beta > 0","Fix likelihood/prior counts that produced zero pseudo-counts; add a smoothing constant if needed"],"exampleFix":null,"handlingStrategy":"validation","validationCode":null,"typeGuard":null,"tryCatchPattern":null,"preventionTips":[],"tags":[],"backgroundTag":null,"analyzedSha":"39ea8a1c6d0b61f071226eff7ede4d4105fed820","analyzedAt":"2026-08-26T03:13:46.626Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}