3

Running the following code:

import matplotlib.pyplot as plt
import numpy as np

def xon (ton, t):
    if ton <= t:
        return (t-ton)/5
    else:
        return 0

vxon = np.vectorize(xon)
t = np.linspace(0, 49, 50)    
xontest = vxon(0, t)
plt.plot(t, xontest, '-')
plt.show()

I get the plot: enter image description here

But when I try to plot for values of ton, wchich are different than zero, e.g.:

xontest = vxon(2, t)

the plot seems to round all the xon values to integer:

enter image description here

What in my code causes such behaviour?

user_185051
  • 426
  • 5
  • 19
  • 1
    If you are using Python2, perhaps changing `return (t-ton)/5` to `return (t-ton)/5.0` would fix it. – zondo Mar 12 '16 at 13:08
  • 1
    Sorry, looked at the wrong number. It is 2.7.9. – user_185051 Mar 12 '16 at 13:40
  • I've deleted my answer, because it was completely off-track. While `5` is an integer, `t` isn't an integer in your case. Rather, it's a NumPy array of `numpy.float64` values or similar. (Might depend on the system, I guess.) Thus Python 2's integer-division-is-floor-division quirk doesn't come into play here. – das-g Mar 12 '16 at 22:27
  • 1
    With `xontest = vxon(2, t)` on Python 2.7.3 and NumPy 1.6.1, I'm getting `xontest == array([ 0. , 0. , 0. , 0.2, 0.4, 0.6, 0.8, 1. , 1.2, 1.4, 1.6, 1.8, 2. , 2.2, 2.4, 2.6, 2.8, 3. , 3.2, 3.4, 3.6, 3.8, 4. , 4.2, 4.4, 4.6, 4.8, 5. , 5.2, 5.4, 5.6, 5.8, 6. , 6.2, 6.4, 6.6, 6.8, 7. , 7.2, 7.4, 7.6, 7.8, 8. , 8.2, 8.4, 8.6, 8.8, 9. , 9.2, 9.4])`, and thus a linear plot for t > 2.0. – das-g Mar 12 '16 at 22:33
  • das-g, actually, your answer was very helpful for me - I understood what to look at. As I just posted below, the problem was in `np.vectorize` in my case. When I added a "float" option to it, my code works. – user_185051 Mar 12 '16 at 22:50

1 Answers1

7

Found the problem. The line

vxon = np.vectorize(xon)

should be written as

vxon = np.vectorize(xon, otypes=[np.float])

Thank you, das-g, for showing me in which direction to dig.

user_185051
  • 426
  • 5
  • 19