jeudi 13 juillet 2017

Return 0.0 and 1.0 if input falls below 0.0 or above 1.0

The goal is to "do something" if the input value falls between (0.0, 1.0).

Otherwise,

  • return 1.0 if input is >= 1.0 or
  • return 0.0 if input is <= 0.0

The straightforward way would be to:

def func(x):
    if x >= 1.0:
        return 1.0
    elif x <= 0.0:
        return 0.0
    else: 
        return do_something(x)

But it's also better to use some max/min trick like this:

def func(x):
    if 0 < x < 1.0:
        return do_something(x)
    else:
        return max(min(x, 1.0), 0.0)

Which coding style more Pythonic returning clipped values if it falls below 0 and above 1 and if otherwise, the float needs to be manipulated?

do_something() is some float manipulation that should return a value between (0.0, 1.0), i.e. exclusive of 0.0 and 1.0.

For simplicity, treat it as:

def do_something(x):
    return x**2

Aucun commentaire:

Enregistrer un commentaire