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
To further explain the question, the (0.0, 1.0) range excludes the 0.0 and 1.0, i.e.
>>> x = 0.231
>>> 0 < x < 1.0
True
So if 0 < x < 1.0
, the desired output has to be put through the do_something()
function that returns a value (0.0, 1.0), e.g.
>>> x**2
0.053361000000000006
>>> 0 < x**2 < 1.0
True
I guess the confusion in the comments comes when you're asking why don't I just do_something()
first then "clamp"/"clip" the outputs, i.e:
>>> x = 0.231
>>> max(min(x**2, 1.0), 0.0)
0.053361000000000006
But let's say you have a negative no. as an input:
>>> x = -0.231
The desired output is 0.0. But if we do just simply do_something()
first then "clamp"/"clip", we get the wrong output:
>>> x = - 0.231
>>> max(min(x**2, 1.0), 0.0)
0.053361000000000006
Perhaps square is a little too simplified to describe do_something()
.
The actual function looks more like this:
def do_something(x):
ratio_y, score_y = 1.5, 0.5
beta = math.log(score_y) / math.log(score_y)**2
return math.exp(beta * math.log(x)**2)'
Due to the asymptote nature of logarithms, the checks for (0.0, 1.0) needs to be explicit before calling the do_something()
function.