TheAlgorithms/Python · error · ValueError

The value of intensity cannot be negative

Error message

The value of intensity cannot be negative

What it means

Raised by malus_law(initial_intensity, angle) when initial_intensity is negative. The function computes transmitted intensity I = I0 * cos^2(angle), which is only meaningful for a non-negative incident intensity. The angle check (0-360) happens after this one, so a call with both invalid raises this error first.

Source

Thrown at physics/malus_law.py:69

    Traceback (most recent call last):
        ...
    ValueError: In Malus Law, the angle is in the range 0-360 degrees
    >>> 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. Clamp instrument readings with max(0, intensity) before calling.
  2. Validate intensity >= 0 and 0 <= angle <= 360 in one pre-call check.
  3. Catch ValueError when processing untrusted measurement data.

Example fix

# before
malus_law(-100, 900)  # ValueError (intensity checked first)

# after
malus_law(max(0, -100), min(900 % 360, 360))  # clamp/normalize first
Defensive patterns

Strategy: validation

Validate before calling

intensity = max(0.0, measured_intensity)  # clamp sensor noise / dark-frame artifacts
if 0 <= angle <= 360:
    malus_law(intensity, angle)

Prevention

When it happens

Trigger: malus_law(-100, 900) from the doctest — negative intensity checked before the out-of-range angle; any call with a signed intensity value from an instrument or subtraction.

Common situations: Detector offsets or dark-frame subtraction producing small negative readings; amplitude-like signed values confused with intensity; batch datasets with occasional negative samples.

Related errors


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