亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

在沒有庫的python中找到x給定y的函數

在沒有庫的python中找到x給定y的函數

慕的地6264312 2022-11-09 16:34:26
在此處為我的練習表輸入圖像描述,我需要編寫一個函數,該函數在沒有任何庫函數的情況下找到函數(稱為 Maxwell_Boltzmann)的給定 y 值的 x 值。所以我嘗試定義函數(稱為 most_probable_speed),它首先找到 Maxwell_Boltzmann 的 y 值的最大值,然后找到達到最大值的 x(在我的代碼中定義為 v)。我用for和if循環嘗試打印v,但它沒有打印出達到最大值的參數v,而是給了我整個向量v。有誰知道我如何打印參數v,達到 y 了嗎?我的代碼是:import numpy as npimport matplotlib.pyplot as pltimport scipyimport scipy.constants as csv= np.linspace(-100,10000,1000) #this are my x values#this is my function, which prints y value in fonction of xdef 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 valuedef 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:               continuereturn highest_probability;m_oxy = 15.99 * cs.u most_probable_speed(v, m = m_oxy, T = 273)  
查看完整描述

1 回答

?
UYOU

TA貢獻1878條經驗 獲得超4個贊

由于 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


查看完整回答
反對 回復 2022-11-09
  • 1 回答
  • 0 關注
  • 125 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號