Reputation: 6202
Let's say I have numbers such as these
Is there a formula that i can apply to these numbers such that I get
Basically I want the number so that if it's above 1 it'll loop around starting at -1...so that my number will always be in the range of [-1,1] and if the number is below -1 it'll wrap around starting at 1.
Upvotes: 0
Views: 1743
Reputation: 76254
You could subtract 1, then mod 2, then subtract 1.
>>> seq = [1.7, 1.2, 0.2, -0.3, -1.2]
>>> [(x-1) % 2 - 1 for x in seq]
[-0.30000000000000004, -0.8, 0.19999999999999996, -0.30000000000000004, 0.7999999999999998]
Although it looks like there is a small loss of precision due to floating point arithmetic. You could round
if you only care about a set number of digits after the decimal point.
>>> [round((x-1) % 2 - 1, 1) for x in seq]
[-0.3, -0.8, 0.2, -0.3, 0.8]
Upvotes: 5