import math


def longwave_radiation(Tmin_C, Tmax_C, ea, Rs, Rso, rh):
    """Calculate the net long-wave radiation.
    Ref: http://www.fao.org/docrep/x0490e/x0490e00.htm Eqn 39
    
    Tmin_C: Minimum temperature during the calculation period
    Tmax_C: Maximum temperature during the calculation period
    ea: Actual vapor pressure in kPa
    Rs: Measured radiation. See below for units.
    Rso: Calculated clear-wky radiation. See below for units.
    rh: Relative humidity in percent
    
    Because the formula uses the ratio of Rs to Rso, their actual units do not matter,
    so long as they use the same units.
    
    Returns back radiation in MJ/m^2/day
    
    Example:
    >>> print("%.1f mm/day" % longwave_radiation(Tmin_C=19.1, Tmax_C=25.1, ea=2.1,
    ...     Rs=14.5, Rso=18.8, rh=50))
    3.5 mm/day
    
    Night time example. Set rh = 40% to reproduce the Rs/Rso ratio of 0.8 used in the paper.
    >>> print("%.1f mm/day" % longwave_radiation(Tmin_C=28, Tmax_C=28, ea=3.402,
    ...     Rs=0, Rso=0, rh=40))
    2.4 mm/day
    """
    # Calculate temperatures in Kelvin:
    Tmin_K = Tmin_C + 273.16
    Tmax_K = Tmax_C + 273.16

    # Stefan-Boltzman constant in MJ/K^4/m^2/day
    sigma = 4.903e-09

    # Use the ratio of measured to expected radiation as a measure of cloudiness, but
    # only if it's daylight
    if Rso:
        cloud_factor = Rs / Rso
    else:
        # If it's nighttime (no expected radiation), then use this totally made up formula
        if rh > 80:
            # Humid. Lots of clouds
            cloud_factor = 0.3
        elif rh > 40:
            # Somewhat humid. Modest cloud cover
            cloud_factor = 0.5
        else:
            # Low humidity. No clouds.
            cloud_factor = 0.8

    # Calculate the longwave (back) radiation (Eqn 39). Result will be in MJ/m^2/day.
    Rnl_part1 = sigma * (Tmin_K ** 4 + Tmax_K ** 4) / 2.0
    Rnl_part2 = (0.34 - 0.14 * math.sqrt(ea))
    Rnl_part3 = (1.35 * cloud_factor - 0.35)
    Rnl = Rnl_part1 * Rnl_part2 * Rnl_part3

    return Rnl