I got the following error and am not sure of its origin:
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
Thus, I wrote
if om_dif > 0:
and I got SIGKILL
The aim is to obtain list k
including the result for negative om_dif
and positive om_dif
.
import numpy as np
import matplotlib.pyplot as plt
omega = np.linspace(0, 1128, 10000)
e = 1.602176634e-19
m_e = 9.1093837015e-31
eps_0 = 8.8541878128e-12
n_0 = 0.00032
c = 1
omega_p = np.sqrt(n_0*e**2/(eps_0*m_e))
k = []
############
for i in omega:
om_dif = omega**2-omega_p**2
if om_dif > 0:
kk = np.sqrt((om_dif)/c**2)
else:
kk = np.sqrt((abs(om_dif))/c**2)
k.append(kk)
##############
v_phi = omega/k
ax.set_xlim(0, 2*omega_p)
ax.set_ylim(-4, 4)
ax.plot(v_phi**2/c**2, omega)
plt.show()
You can avoid the loop by using numpy
functions to perform the computation directly using arrays. (It is also much faster)
import numpy as np
import matplotlib.pyplot as plt
omega = np.linspace(0, 1128, 10000)
e = 1.602176634e-19
m_e = 9.1093837015e-31
eps_0 = 8.8541878128e-12
n_0 = 0.00032
c = 1
omega_p = np.sqrt(n_0*e**2/(eps_0*m_e))
k = np.sqrt((np.abs(omega**2 - omega_p**2))/c**2)
fig, ax=plt.subplots(1)
v_phi = omega / np.array(k)
ax.set_xlim(0, 2*omega_p)
ax.set_ylim(-4, 4)
ax.plot(v_phi**2/c**2, omega)
plt.show()
To specifically address the error message, the issue lies in that you correctly iterate over the omega array, but you then operate on the entire array instead of the array's value for id i
[...]
for i in omega:
om_dif = omega[i]**2-omega_p[i]**2
[...]
You would also gain compute time by not bothering testing if om_dif
is positive and always applying the abs()
function to your value.
for i in omega:
om_dif = omega[i]**2-omega_p[i]**2
k.append(np.sqrt((abs(om_dif))/c**2))
On the actual method, @ Andrea 's answer seems to best leverage the numpy
library.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.