enter image description here对于我的练习薄,我需要编写一个函数,该函数在没有任何库函数的情况下为给定y值的函数(称为Maxwell_Boltzmann)找到x值。因此,我尝试定义一个函数(称为most_probable_speed),该函数首先查找Maxwell_Boltzmann的y值的最大值,然后查找为其x(在我的代码中定义为v)的最大值。我使用for和if循环尝试打印v,但是它并没有打印出达到最大值的参数v,但给了我整个矢量v。有人知道我如何打印参数v,为此y已到达?
我的代码是:
import numpy as np
import matplotlib.pyplot as plt
import scipy
import scipy.constants as cs
v= np.linspace(-100,10000,1000) #this are my x values
#this is my function, which prints y value in fonction of x
def Maxwell_Boltzmann(v, m, T):
''' calculate the Maxwell-Boltzmann distribution
for the speed of the chemical elements
3 parameters: -the speed of the particle
-its masse
-its temperature'''
y = np.sqrt(2/np.pi) * (m /( cs.k * T))**(3/2) * v**2 * np.exp(-m*v**2/(2 * cs.k * T))
return y;
# this is the function which is suppose to find the x value given the y value
def most_probable_speed(v,m,T):
'''determine the most probable speed of a given mass and temperature'''
x = Maxwell_Boltzmann(v, m, T) #put the y values of Maxwel_B for all x in an array named x
highest_probability = np.amax(x) #Return the maximum value of y
# I want to print the value of v for whcih Maxwell_Boltzmann(v, m, T)= highest_probability
for a in Maxwell_Boltzmann(v, m, T):
if a == highest_probability:
print(v)
else:
continue
return highest_probability;
m_oxy = 15.99 * cs.u
most_probable_speed(v, m = m_oxy, T = 273)
由于y的每个元素对应于同一索引中v的元素(这是您想要的x值),因此您可以使用enumerate
为您提供每个值的索引并打印出相应的x
比整个矢量:
def most_probable_speed(v,m,T):
'''determine the most probable speed of a given mass and temperature'''
x = Maxwell_Boltzmann(v, m, T) #put the y values of Maxwel_B for all x in an array named x
highest_probability = np.amax(x) #Return the maximum value of y
# I want to print the value of v for whcih Maxwell_Boltzmann(v, m, T)= highest_probability
for idx, a in enumerate(Maxwell_Boltzmann(v, m, T)):
if a == highest_probability:
print(v[idx])
else:
continue