python - 在没有库的python中找到x给定y的函数
问题描述
在此处为我的练习表输入图像描述,我需要编写一个函数,该函数在没有任何库函数的情况下找到函数(称为 Maxwell_Boltzmann)的给定 y 值的 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
但是,您调用 Maxwell_Boltzmann 函数两次。如果您只是想找到对应于最高 y 值的 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_idx = np.argmax(x) # Return the index of the maximum value of y
print(v[highest_probability_idx])
在这里,np.argmax
返回返回数组中最大值的索引,然后您可以使用它来访问v
向量中相应的 x
推荐阅读
- memory - tomcat内存计算不同
- c++ - 在清除的屏幕上打印从 1 到 10 的每个数字,它们之间有一些时间
- flutter - 显示列表时避免多个具有相同值的数据
- r - DT 表中的单个按钮
- javascript - 具有相同站点的 js-cookie 无且安全
- mysql - 在同一行按名称分组,不包括 NULL 值
- flutter - 使用 GitHub 操作创建文件夹并注入 JSON 文件
- html - 无法为 mydatepicker 插入角色或动态更新选项卡索引
- docker - 错误:无法在节点“rabbit@localhost”上执行操作
- object - 我可以编写一个行为类似于哈希的对象吗?