{"record":{"id":"bd1a3b25a79ed960","repo":"TheAlgorithms/Python","slug":"undefined-for-non-natural-numbers","errorCode":null,"errorMessage":"Undefined for non-natural numbers","messagePattern":"Undefined for non-natural numbers","errorType":"exception","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"maths/chudnovsky_algorithm.py","lineNumber":42,"sourceCode":"\n    >>> pi(10)\n    '3.14159265'\n    >>> pi(100)\n    '3.14159265358979323846264338327950288419716939937510582097494459230781640628620899862803482534211706'\n    >>> pi('hello')\n    Traceback (most recent call last):\n        ...\n    TypeError: Undefined for non-integers\n    >>> pi(-1)\n    Traceback (most recent call last):\n        ...\n    ValueError: Undefined for non-natural numbers\n    \"\"\"\n\n    if not isinstance(precision, int):\n        raise TypeError(\"Undefined for non-integers\")\n    elif precision < 1:\n        raise ValueError(\"Undefined for non-natural numbers\")\n\n    getcontext().prec = precision\n    num_iterations = ceil(precision / 14)\n    constant_term = 426880 * Decimal(10005).sqrt()\n    exponential_term = 1\n    linear_term = 13591409\n    partial_sum = Decimal(linear_term)\n    for k in range(1, num_iterations):\n        multinomial_term = factorial(6 * k) // (factorial(3 * k) * factorial(k) ** 3)\n        linear_term += 545140134\n        exponential_term *= -262537412640768000\n        partial_sum += Decimal(multinomial_term * linear_term) / exponential_term\n    return str(constant_term / partial_sum)[:-1]\n\n\nif __name__ == \"__main__\":\n    n = 50\n    print(f\"The first {n} digits of pi is: {pi(n)}\")","sourceCodeStart":24,"sourceCodeEnd":60,"githubUrl":"https://github.com/TheAlgorithms/Python/blob/f5988cc09713315817df6a7e327e258013a94440/maths/chudnovsky_algorithm.py#L24-L60","documentation":"Raised by pi() in maths/chudnovsky_algorithm.py when precision is an int but less than 1. The Chudnovsky series is summed for ceil(precision/14) iterations to produce exactly `precision` significant digits; zero or negative precision has no mathematical meaning, so it is rejected with ValueError (undefined for non-natural numbers).","triggerScenarios":"Calling pi(0) or pi(-1) — any integer precision < 1. Note pi(-1.5) hits the earlier TypeError instead, since the isinstance check runs first.","commonSituations":"Precision derived from a formula that can reach 0 (e.g. len(str) - 20 for short inputs); inverted conditionals that pass -1 as an error sentinel; user-facing parameters left at 0 by default.","solutions":["Clamp or validate precision >= 1 before calling: precision = max(precision, 1) if a fallback is acceptable, else raise your own error.","Fix the upstream computation that produced a non-positive precision.","Treat 0/negative precision as invalid input at your API boundary with a clear message."],"exampleFix":"# before\npi(-1)  # ValueError: Undefined for non-natural numbers\n\n# after\nprecision = 50\nif precision < 1:\n    raise ValueError('precision must be >= 1')\nresult = pi(precision)","handlingStrategy":"validation","validationCode":"if precision < 1:\n    raise ValueError(f'precision must be >= 1, got {precision}')\ndigits = pi(precision)","typeGuard":null,"tryCatchPattern":"try:\n    digits = pi(precision)\nexcept ValueError as e:\n    if 'non-natural' in str(e):\n        digits = pi(1)  # deliberate fallback to minimum precision\n    else:\n        raise","preventionTips":["Clamp user-supplied precision: precision = max(1, int(precision)).","Watch formulas like len(s) - 20 that go negative for short inputs."],"tags":["maths","pi","decimal","validation","valueerror"],"backgroundTag":null,"analyzedSha":"f5988cc09713315817df6a7e327e258013a94440","analyzedAt":"2026-08-14T17:30:07.041Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}