TheAlgorithms/Python · error · ValueError

In Malus Law, the angle is in the range 0-360 degrees

Error message

In Malus Law, the angle is in the range 0-360 degrees

What it means

Raised by malus_law(initial_intensity, angle) when angle < 0 or angle > 360. The formula I = I0*cos^2(radians(angle)) uses degrees over one full turn; inputs outside [0, 360] are rejected rather than wrapped. This check runs only after the negative-intensity check passes.

Source

Thrown at physics/malus_law.py:72

    >>> round(malus_law(10,900),2)
    Traceback (most recent call last):
        ...
    ValueError: In Malus Law, the angle is in the range 0-360 degrees
    >>> round(malus_law(-100,900),2)
    Traceback (most recent call last):
        ...
    ValueError: The value of intensity cannot be negative
    >>> round(malus_law(100,180),2)
    100.0
    >>> round(malus_law(100,360),2)
    100.0
    """

    if initial_intensity < 0:
        raise ValueError("The value of intensity cannot be negative")
        # handling of negative values of initial intensity
    if angle < 0 or angle > 360:
        raise ValueError("In Malus Law, the angle is in the range 0-360 degrees")
        # handling of values out of allowed range
    return initial_intensity * (math.cos(math.radians(angle)) ** 2)


if __name__ == "__main__":
    import doctest

    doctest.testmod(name="malus_law")

View on GitHub (pinned to f5988cc097)

Solutions

  1. Normalize the angle into [0, 360]: angle % 360 (and add 360 first for negatives).
  2. Convert radians with math.degrees() before calling.
  3. Pre-validate 0 <= angle <= 360 alongside intensity >= 0.

Example fix

# before
malus_law(100, -30)   # ValueError
malus_law(100, 1.57)  # wrong: radians silently accepted as degrees

# after
malus_law(100, (-30) % 360)          # 330
malus_law(100, math.degrees(1.57))    # ~90
Defensive patterns

Strategy: validation

Validate before calling

angle_deg = angle % 360  # normalizes negatives and >360 wraps
if not (0 <= angle_deg <= 360):
    raise ValueError('angle normalization failed')
malus_law(initial_intensity, angle_deg)

Prevention

When it happens

Trigger: malus_law(100, -30) or malus_law(100, 400); supplying radians (e.g. 6.28) works numerically but is wrong physics — degrees are expected.

Common situations: Passing radians instead of degrees; angles accumulated by integration that exceed 360; negative angles from clockwise-rotation conventions not normalized.

Related errors


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