0
In[2]: from numpy import *
In[3]: alpha = lambda x: piecewise(x,[x <= 4, 4 < x <= 24, x > 24], [10, 20, 50])
In[4]: print(alpha(5))
0
In[5]: print(alpha(3))
10
In[6]: print(alpha(26))
0

Why isn't this working? there are 3 conditions and 3 functions

  • 1
    Please give us the intended behaviour. Your code works. – yyny Nov 17 '16 at 01:32
  • Let me rephrase myself, your code does _not_ work. Use `alpha(array([5]))`. The first argument to piecewise is a [`ndarray`](https://docs.scipy.org/doc/numpy/reference/generated/numpy.piecewise.html) – yyny Nov 17 '16 at 01:44
  • I have a class which can take in variables as f(t). i'd like to use piecewise instead of creating a function f(t) with if and elif statements. I need to be able to send in single values and have the corresponding value returned – Alexander Mathers Nov 17 '16 at 01:52
  • The problem is that the class does not send a variable but rather single values at a time in a for loop. I know that with a function with if and elif statements this works fine but i thought piecewise could do the same just more elegantly and less code. Send in single numbers and output based on conditions – Alexander Mathers Nov 17 '16 at 02:02

1 Answers1

1

Found out that select does what i want it to

In[2]: from numpy import *
In[3]: alpha = lambda x: select([x <= 4, (4 < x) & (x <= 24), x > 24], [10, 20, 50])
In[4]: print(alpha(5))
20
In[5]: print(alpha(3))
10
In[6]: print(alpha(26))
50
  • Aside: `from numpy import *` is a bad idea -- it shadows builtins like `any` and `all` with versions which behave differently. – DSM Nov 17 '16 at 03:02
  • What do you mean by that? – Alexander Mathers Nov 17 '16 at 11:32
  • @Alexandermathers That importing a module into the global namespace might 'shadow' existing functions, thereby making them unaccessible. If I create a module `def print(): pass`, and import it globally, `print(":(");` no longer prints anything to `stdout`. – yyny Nov 18 '16 at 16:37
  • @AlexanderMathers: try `print(bool(any(i > 3 for i in [0,1])))` at a fresh console. Then do `from numpy import *` and try it again. You'll get False the first time, and True the second. – DSM Nov 19 '16 at 15:28