import math


def SafeAcos(x):
    """ Same as ``math.acos(x)`` but if x is out of range, it is "clamped" to the 
        nearest valid value. The value returned is in range 0...pi, the same as 
        the standard `math.acos`_ function. 
    """
    # Check limit conditions
    if x <= -1.0:
        return math.pi
    if x >= 1.0:
        return 0.0
    # Value is in the domain - use standard acos function
    return math.acos(x)