Reputation: 22011
Can the following method be written any shorter (without semicolons) in Python in a way I have not seen?
@staticmethod
def __add(a, b):
value = a + b
if value > 1:
integer = int(value)
if value == integer:
return 1.0
return value - integer
if value < 0:
integer = int(value)
if value == integer:
return 0.0
return value - integer + 1
return value
The code is like %
except that it allows the endpoint of whatever the code is modding the end value to.
Upvotes: 0
Views: 152
Reputation: 22011
You can use the following method. Color values outside the range of 0.0 - 1.0
are correctly modded.
@staticmethod
def __mod(value):
div, mod = divmod(value, 1)
if div > 0 and not mod:
return 1.0
return mod
Upvotes: 0
Reputation: 30969
Why not:
value = (a + b) % 1.0
if (value == 0.0 and a + b > 0) value = 1.0
I'm not sure why the a + b > 0
condition is necessary on the second line, but it matches the behavior in your code of returning 1 if a + b
is a positive integer and 0 if a + b
is zero or a negative integer. What is the specific reason you want to return 1 when a + b
is an integer rather than 0?
EDIT: Looking at the documentation further, that first line should probably be value = fmod(a + b, 1.0) + (1.0 if a + b < 0.0 else 0.0)
(fmod
recommended for more precision, with that second part to correct the sign of the result).
Upvotes: 0