I'm trying to do the KDB Q equivalent of Python's np.clip, so floats in the range -1 < x < 1 are returned, and numbers outside of this range return -1 and 1 respectively.
I'm trying to do the KDB Q equivalent of Python's np.clip, so floats in the range -1 < x < 1 are returned, and numbers outside of this range return -1 and 1 respectively.
Here's another one, just to add to the list
q)clip: {-1 | 1 & 0f ^ x}
q)clip -2 -1 -0.5 0 0.5 1 2 0N 0n
-1 -1 -0.5 0 0.5 1 1 0 0
the function:
clip:{[b1;b2;x] ?[null x;abs[type x]$0n;b1|x&b2]}
should be the function you are looking for.
So you now just need to apply
clip[-1;1;]
to any list you wish.
You can define it yourself quite easily using a nested vector conditional:
q)clip:{?[x<-1;-1;?[x>1;1;x]]}
q)l:(neg 2) + 10?4.0
q)l
0.4812058 1.730526 -0.9011735 -1.769899 -0.9757369 -1.075957 -1.651039 -1.590227 1.468439 0.911411
q)clip l
0.4812058 1 -0.9011735 -1 -0.9757369 -1 -1 -1 1 0.911411