Arrays and Plotting¶
da PowerShell -- jupyter nbconvert --to html notebook.ipynb¶
NumPy and Array Computing¶
In [1]:
import numpy as np # module for arrays
def f(x):
return x**2
n = 5 # number of points
dx = 1.0/(n-1) # x spacing in [0,1]
# memozizzo in due List
xlist = [i*dx for i in range(n)]
ylist = [f(x) for x in xlist]
# memorizzo in due array
x = np.array(xlist) # turn list xlist into array
y = np.array(ylist)
# genero array x equispaziato
x = np.linspace(0, 1, n) # n points in [0, 1]
print('x =',x)
y = np.zeros(n) # n zeros (float data type)
for i in range(n):
y[i] = f(x[i])
x = [0. 0.25 0.5 0.75 1. ]
Gli array non accettano "append"¶
In [3]:
import numpy as np
from math import cos
n = 11
x1 = np.linspace(0,1,n)
y1 = np.zeros(n) # n zeros (float data type)
for i in range(len(x)):
y1[i] = cos(x1[i])
# numpy accetta come input un array
z1 = np.cos(x1) # x1: array, y1: array
#
# math funzioni accettano solo scalari
Un modo compatto, zenza loop for¶
In [5]:
import numpy as np
n = 100
x = np.linspace(0, 4, n+1)
y = np.exp(-x)*np.sin(2*np.pi*x)
Plotting Curves with Matplotlib¶
In [7]:
import matplotlib.pyplot as plt
import numpy as np
n = 100
x = np.linspace(0, 4, n+1)
y = np.exp(-x)*np.sin(2*np.pi*x)
plt.figure(figsize=(6, 3), dpi=96)
plt.plot(x, y, label='exp(-x)*sin(2$\pi$ x)')
plt.xlabel('x') # label on the x axis
plt.ylabel('y') # label on the y axis
plt.legend() # mark the curve
plt.axis([0, 4, -0.5, 0.8]) # [tmin, tmax, ymin, ymax]
plt.title('My First Matplotlib Demo')
#plt.savefig('fig.pdf') # make PDF image for reports
#plt.savefig('fig.png') # make PNG image for web pages
plt.show()
Multiple Curves in the Same Plot¶
In [5]:
import matplotlib.pyplot as plt
import numpy as np
def f1(x):
return np.exp(-x)*np.sin(2*np.pi*x)
def f2(x):
return np.exp(-2*x)*np.sin(4*np.pi*x)
x = np.linspace(0, 8, 401)
y1 = f1(x)
y2 = f2(x)
plt.figure(figsize=(6, 3), dpi=96)
plt.plot(x, y1, 'r--', label='exp(-x)*sin(2$\pi$ x)')
plt.plot(x, y2, 'g:', label='exp(-2*x)*sin(4$\pi$ x)')
plt.xlabel('x')
plt.ylabel('y')
plt.legend()
plt.title('Plotting two curves in the same plot')
plt.savefig('fig_two_curves.png')
plt.show()
Plotting a user.specified function¶
In [1]:
import plot_input
Plotting Discontinuous and Piecewise-Defined Functions - ( a tratti )¶
Così non funziona¶
In [12]:
import matplotlib.pyplot as plt
import numpy as np
def H(x):
if x < 0:
return 0
else:
return 1
x = np.linspace(-10, 10, 5) # few points (simple curve)
y = H(x)
plot(x, y)
--------------------------------------------------------------------------- ValueError Traceback (most recent call last) Cell In[12], line 11 8 return 1 10 x = np.linspace(-10, 10, 5) # few points (simple curve) ---> 11 y = H(x) 12 plot(x, y) Cell In[12], line 5, in H(x) 4 def H(x): ----> 5 if x < 0: 6 return 0 7 else: ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
Con un for carico y --> funziona¶
In [20]:
import numpy as np
import matplotlib.pyplot as plt
n = 5
x = np.linspace(-5, 5, n+1)
y = np.zeros(n+1)
for i in range(len(x)):
y[i] = H(x[i])
plt.figure(figsize=(6, 3), dpi=96)
plt.plot(x,y)
plt.show()
Un altro sistema è quello di usare vectorize¶
In [23]:
import numpy as np
import matplotlib.pyplot as plt
# funzione scalare con if
def f_scalar(x):
if x < 0:
return x**2
else:
return np.sqrt(x)
# vettorializzazione
f = np.vectorize(f_scalar)
# dominio
x = np.linspace(-10, 10, 400)
# valutazione
y = f(x)
# grafico
plt.figure(figsize=(6, 3), dpi=96)
plt.plot(x, y)
plt.xlabel("x")
plt.ylabel("f(x)")
plt.title("Funzione con if usando np.vectorize")
plt.grid(True)
plt.show()
Making a Movie of a Plot¶
$$\large f(x) = \frac{1}{\sqrt{2\pi}} \frac{1}{s} exp\left[ -\frac{1}{2} \left( \frac{x-m}{s} \right)^2 \right] $$
In [3]:
import numpy as np
from vpython import canvas, graph, gcurve, rate, color
def gauss(x, m, s):
return np.exp(-0.5*((x-m)/s)**2) / (np.sqrt(2*np.pi)*s)
# dominio
m = 0.0
x = np.linspace(-6, 6, 800)
# parametri di sigma
s = 2.0
ds = -0.02
s_min = 0.2
# canvas + graph (fondamentale)
scene = canvas(title="Gaussiana con sigma variabile")
g = graph(
xtitle="x",
ytitle="f(x)",
width=600,
height=300,
ymin=0, # <<< FISSO
ymax=2 # <<< FISSO
)
# statement fodamentale
curve = gcurve(color=color.blue)
# ciclo temporale (stile VPython puro)
while s > s_min:
rate(30)
# costruisco i dati come nel tuo codice
data = []
for xi in x:
data.append([xi, gauss(xi, m, s)])
curve.data = data # <<< QUI è la chiave, statement fondamentale
s += ds
More Useful Array Operations¶
Copiare un Array - Creare un Array della stessa dimensione di uno dato¶
In [45]:
import numpy as np
x = np.linspace(0,10,101)
a = np.zeros(x.shape, x.dtype)
# oppure
a = x.copy()
b = np.zeros_like(x) # zeros and same size as x
c = np.asarray(a)
Estrarre elementi da un Array¶
In [55]:
import numpy as np
a = np.linspace(1,8,8)
print(a)
a[[1,6,7]] = 10 # vario il valore di 3 elementi
print(a)
a[range(2,8,3)] = -2 # vario il valore di 3 elementi - # same as a[2:8:3] = -2
print(a)
print(a<0)
print(a[a<0]) # pick out all negative elements
a[a < 0] = a.max() # if a[i]<0, set a[i]=10
print(a)
[1. 2. 3. 4. 5. 6. 7. 8.] [ 1. 10. 3. 4. 5. 6. 10. 10.] [ 1. 10. -2. 4. 5. -2. 10. 10.] [False False True False False True False False] [-2. -2.] [ 1. 10. 10. 4. 5. 10. 10. 10.]
In [59]:
import numpy as np
A = np.zeros((3,4)) # 3x4 table of numbers
A[0,0] = -1
A[1,0] = 1
A[2,0] = 10
A[0,1] = -5
A[2,3] = -100
# can also write (as for nested lists)
A[2][3] = -100
In [ ]: