![](/img/trans.png)
[英]How do I convert this Matlab code with meshgrid and arrays to Python code?
[英]How do I convert this code from matlab to python?
我正在嘗試將 matlab 中的計算轉換為 python。這是 matlab 中的代碼:
% Solving for the bandpass correction
T = 8050; % temperature in kelvin
c = 2.99e10; % speed of light in cm/s
h = 6.626e-27; % planck constant in ergs
k = 1.38e-16; % boltzmann constant in erg/K
x1 = 3e-4; % lower wavelength in cm
x2 = 13e-4; % upper wavelength in cm
fun = @(x) ((2 * h * c^2) ./ x.^5) ./ (exp((h * c) ./ (x * k * T)) - 1); % planck function
f_deriv = @(x) ((2 * h^2 * c^3) ./ (x.^6 * k)) .* (exp((h .* c) ./ (x* k * T)) ./ (T * (exp((h * c) ./ (x * k * T)) - 1).^2));
numerator = integral(f_deriv,x1,x2);
denominator = (4 * integral(fun,x1,x2));
beta = numerator / denominator;
fprintf('The numerator is %f \n',numerator)
fprintf('The denominator is %f \n',denominator)
fprintf('The bandpass value is %f \n',beta)
這是我在 python 中對其進行編碼的嘗試:
# Solving for the bandpass correction:
from scipy.integrate import quad
import numpy as np
T = 8050 # temperature in kelvin
c = 2.99e10 # speed of light in cm/s
h = 6.626e-27 # planck constant in ergs
k = 1.38e-16 # boltzmann constant in erg/K
x1 = 3e-4 # lower wavelength in cm
x2 = 13e-4 # upper wavelength in cm
def p_function(x):
return ((2 * h * c ** 2) / x ** 5) / (np.exp((h * c)/(x * k * T)) - 1) # The Planck function
def p_deriv(x):
return ((2 * h ** 2 * c ** 3) / (x ** 6 * k)) * (np.exp((h * c)/(x * k * T))/(T * (np.exp((h * c) / (x * k * T)) - 1) ** 2))
numerator = quad(p_deriv, x1, x2)
denominator = 4 * quad(p_function, x1, x2)
beta = numerator[0] / denominator[0]
print("The numerator is", numerator[0])
print("The denominator is", denominator[0])
print("The bandpass value is", beta)
兩者之間的 beta 值不一致,我看不出是什么導致了差異。 我將不勝感激任何有助於協調這一點的幫助。 謝謝!
通常在翻譯 MATLAB 時,確保形狀/大小正確很重要。 但是當我在 Octave 中運行您的代碼時,我看到所有變量都是 (1,1),“標量”。 所以尺寸應該不是問題。
讓我們檢查 function 值:
>> fun(1)
ans = 0.066426
>> f_deriv(1)
ans = 0.066432
您的numpy
值看起來相同:
In [3]: p_function(1)
Out[3]: 0.06642589646577152
In [4]: p_deriv(1)
Out[4]: 0.06643181982384715
以及整合結果:
>> numerator
numerator = 795765635.47589
In [7]: numerator = quad(p_deriv, x1, x2)
In [8]: numerator
Out[8]: (795765635.4758892, 0.030880182071769013)
閱讀文檔我們看到quad
返回(默認)2 個值,積分和誤差估計。 元組的第一個與 MATLAB 匹配。您確實使用了 numerator numerator[0]
。
denominator
也一樣——注意在乘法之前從元組中提取值:
In [10]: denominator = 4 * quad(p_function, x1, x2)[0]
In [11]: denominator
Out[11]: 2568704689.659281
In [12]: numerator[0] / denominator
Out[12]: 0.309792573151506
>> beta
beta = 0.30979
如果不進行校正,結果會大 4 倍
In [13]: denominator = 4 * quad(p_function, x1, x2)
In [14]: denominator
Out[14]:
(642176172.4148202,
0.006319781838840299,
642176172.4148202,
0.006319781838840299,
642176172.4148202,
0.006319781838840299,
642176172.4148202,
0.006319781838840299)
In [15]: numerator[0] / denominator[0]
Out[15]: 1.239170292606024
有時(甚至經常)我們需要逐步測試值。 即使從頭開始開發numpy
代碼,我也會測試所有步驟。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.