TheAlgorithms/Python · error · ValueError

maclaurin_cos() requires either an int or float for theta

Error message

maclaurin_cos() requires either an int or float for theta

What it means

Raised by maclaurin_cos() in maths/maclaurin_series.py when theta is not an int or float. The function approximates cos(theta) via its Maclaurin series after normalizing theta with `theta = float(theta)`, so only real numeric radians are accepted. Any other type fails this isinstance gate before computation.

Source

Thrown at maths/maclaurin_series.py:99

    Traceback (most recent call last):
        ...
    ValueError: maclaurin_cos() requires either an int or float for theta
    >>> maclaurin_cos(10, -30)
    Traceback (most recent call last):
        ...
    ValueError: maclaurin_cos() requires a positive int for accuracy
    >>> maclaurin_cos(10, 30.5)
    Traceback (most recent call last):
        ...
    ValueError: maclaurin_cos() requires a positive int for accuracy
    >>> maclaurin_cos(10, "30")
    Traceback (most recent call last):
        ...
    ValueError: maclaurin_cos() requires a positive int for accuracy
    """

    if not isinstance(theta, (int, float)):
        raise ValueError("maclaurin_cos() requires either an int or float for theta")

    if not isinstance(accuracy, int) or accuracy <= 0:
        raise ValueError("maclaurin_cos() requires a positive int for accuracy")

    theta = float(theta)
    div = theta // (2 * pi)
    theta -= 2 * div * pi
    return sum((-1) ** r * theta ** (2 * r) / factorial(2 * r) for r in range(accuracy))


if __name__ == "__main__":
    import doctest

    doctest.testmod()

    print(maclaurin_sin(10))
    print(maclaurin_sin(-10))
    print(maclaurin_sin(10, 15))

View on GitHub (pinned to f5988cc097)

Solutions

  1. Convert to float at the call site: maclaurin_cos(float(theta)).
  2. Sanitize external inputs once at ingestion, then pass validated floats through your code.
  3. Check argument order — this error often means a non-angle value was passed as the first parameter.

Example fix

# before
maclaurin_cos(angle_str)  # angle_str = '1.57'

# after
maclaurin_cos(float(angle_str))
Defensive patterns

Strategy: type-guard

Validate before calling

theta = float(theta)  # raises your own TypeError early if theta is not numeric

Type guard

def is_valid_theta(x) -> bool:
    return isinstance(x, (int, float)) and not isinstance(x, bool)

Prevention

When it happens

Trigger: maclaurin_cos('0'), maclaurin_cos(None), maclaurin_cos(complex(1,2)), or passing a value straight from a text field/config without conversion.

Common situations: Angles from UI text inputs, CSV/JSON string fields, or accidentally passing the wrong positional argument (e.g. a label where the angle goes).

Related errors


AI-assisted analysis of TheAlgorithms/Python@f5988cc097 (2026-08-14). Data as JSON: /api/errors/207fe72caaa9b935. Report an issue: GitHub.