{"record":{"id":"4e017b12d0c68721","repo":"TheAlgorithms/Python","slug":"input-must-be-a-positive-number","errorCode":null,"errorMessage":"Input must be a positive number.","messagePattern":"Input must be a positive number\\.","errorType":"exception","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"maths/fast_inverse_sqrt.py","lineNumber":39,"sourceCode":"    >>> fast_inverse_sqrt(4)\n    0.49915357479239103\n    >>> fast_inverse_sqrt(4.1)\n    0.4932849504615651\n    >>> fast_inverse_sqrt(0)\n    Traceback (most recent call last):\n        ...\n    ValueError: Input must be a positive number.\n    >>> fast_inverse_sqrt(-1)\n    Traceback (most recent call last):\n        ...\n    ValueError: Input must be a positive number.\n    >>> from math import isclose, sqrt\n    >>> all(isclose(fast_inverse_sqrt(i), 1 / sqrt(i), rel_tol=0.00132)\n    ...     for i in range(50, 60))\n    True\n    \"\"\"\n    if number <= 0:\n        raise ValueError(\"Input must be a positive number.\")\n    i = struct.unpack(\">i\", struct.pack(\">f\", number))[0]\n    i = 0x5F3759DF - (i >> 1)\n    y = struct.unpack(\">f\", struct.pack(\">i\", i))[0]\n    return y * (1.5 - 0.5 * number * y * y)\n\n\nif __name__ == \"__main__\":\n    from doctest import testmod\n\n    testmod()\n    # https://en.wikipedia.org/wiki/Fast_inverse_square_root#Accuracy\n    from math import sqrt\n\n    for i in range(5, 101, 5):\n        print(f\"{i:>3}: {(1 / sqrt(i)) - fast_inverse_sqrt(i):.5f}\")\n","sourceCodeStart":21,"sourceCodeEnd":55,"githubUrl":"https://github.com/TheAlgorithms/Python/blob/f5988cc09713315817df6a7e327e258013a94440/maths/fast_inverse_sqrt.py#L21-L55","documentation":"Raised by fast_inverse_sqrt() in maths/fast_inverse_sqrt.py when the input number is <= 0. The function implements the Quake III fast inverse square root via bit-level struct reinterpretation, and the magic-constant trick is only meaningful for positive, finite IEEE-754 floats; zero and negatives have no real inverse square root.","triggerScenarios":"Calling fast_inverse_sqrt(0), fast_inverse_sqrt(-1), or fast_inverse_sqrt(-0.5). The `if number <= 0` guard raises ValueError before the struct pack/unpack bit hack runs.","commonSituations":"Normalizing zero-length vectors (1/sqrt(0) is infinite), passing unnormalized sensor data containing zeros, sign errors when squaring/absolute values are omitted, or feeding NaN-adjacent computed magnitudes into graphics or physics code.","solutions":["Guard inputs: skip or clamp values <= 0 before calling (e.g. treat 0 magnitude as a special case).","Use max(number, 1e-12) style epsilon flooring when near-zero magnitudes are expected.","For exact (rather than approximate) results use 1 / math.sqrt(number), which still requires number > 0.","Validate data upstream so zero/negative magnitudes never reach the routine."],"exampleFix":"# before\ninv_len = fast_inverse_sqrt(x*x + y*y)  # raises when vector is (0, 0)\n\n# after\nmag_sq = x*x + y*y\nif mag_sq <= 0:\n    inv_len = 0.0\nelse:\n    inv_len = fast_inverse_sqrt(mag_sq)","handlingStrategy":"validation","validationCode":"if number <= 0:\n    raise ValueError(f'fast_inverse_sqrt requires positive input, got {number}')\nresult = fast_inverse_sqrt(number)","typeGuard":"def is_positive_finite(x: object) -> bool:\n    import math\n    return isinstance(x, (int, float)) and math.isfinite(x) and x > 0","tryCatchPattern":"try:\n    y = fast_inverse_sqrt(x)\nexcept ValueError:\n    y = 0.0  # degenerate vector / non-positive magnitude fallback","preventionTips":["Special-case zero-magnitude vectors before normalizing.","Use abs() or squared magnitudes so sign errors cannot reach the function.","Floor magnitudes with a small epsilon when near-zero inputs are expected."],"tags":["math","inverse-sqrt","negative-value","graphics","valueerror"],"backgroundTag":null,"analyzedSha":"f5988cc09713315817df6a7e327e258013a94440","analyzedAt":"2026-08-14T17:30:07.041Z","schemaVersion":2},"datasetVersion":"2026-08-15T17:31:12.345Z"}