Grundstück Piecewise-Funktion in Python

Ich möchte zeichnen Sie die folgende stückweise Funktion in Python mit Matplotlib, von 0 bis 5.

f(x) = 1, x != 2; f(x) = 0, x = 2

In Python...

def f(x):
 if(x == 2): return 0
 else: return 1

Mithilfe von NumPy ich ein array erstellen,

x = np.arange(0., 5., 0.2)

    array([ 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])

Ich habe versucht, Dinge wie...

import matplotlib.pyplot as plt
plt.plot(x,f(x))

... Oder

vecfunc = np.vectorize(f)
result = vecfunc(t)

... Oder

def piecewise(x):
 if x == 2: return 0
 else: return 1

import matplotlib.pyplot as plt
x = np.arange(0., 5., 0.2)
plt.plot(x, map(piecewise, x))

ValueError: x and y must have same first dimension

Aber ich bin nicht mit dieser richtig funktioniert, und bin jetzt nur zufällig zu raten, wie dies zu tun.

Einige Antworten ab, um es... Aber die Punkte sind verbunden in einer Linie auf dem Grundstück. Wie wir Plotten die Punkte?

Grundstück Piecewise-Funktion in Python

Schreibe einen Kommentar