[SciPy-User] Heaviside function in vector form

David J Pine djpine at gmail.com
Sun Jul 6 13:44:48 EDT 2014


Use NumPy "where" function.

np.where(x<0., 0., 1.)



On Saturday, July 5, 2014, Barrett B <barrett.n.b at gmail.com> wrote:

> I am trying to code the Heaviside function in vector form. There are
> several different versions of this, but essentially, f(x) = 1 whenever x >=
> 0, and f(x) = 0 whenever x < 0. Here is what I have so far (keep in mind, x
> is a vector here):
>
> =========
>
> def Heaviside(x):
>     mult = -100.0; diff = mult*(x - Theta_syn);
> #    print x
>     if abs(diff) < 50: #if x is close to Theta_syn
>         return 1.0/(1 + np.exp(diff))
>     if x < Theta_syn:
>         return 0
>     return 1 #otherwise
> #    return 1.0/(1 + np.exp(diff))
>
> =========
>
> which produces the following error:
>
> ValueError: The truth value of an array with more than one element is
> ambiguous. Use a.any() or a.all()
>
> BTW, if I were to comment out every line except the first and last, it
> runs fine.
>
> See what I'm trying to do? Basically, I want to check whether current
> value of diff is not very large. But I don't know how to do this without
> rewriting the code to include for loops, which is what I've been trying to
> get away from all along?
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.scipy.org/pipermail/scipy-user/attachments/20140706/d2266576/attachment.html>


More information about the SciPy-User mailing list