以下,就是通過定義式得來的復(fù)數(shù)域gamma函數(shù),未使用近似算:
function ret=Gamma(z)
if isreal(z)
ret=gamma(z);
else
if real(z) >= 0
rt=@(x)(-1).^x ./ (gamma(x+1).*(x+z));
ret=integral(@(x)exp(-x).*x.^(z-1), 1, Inf)+sum(rt(0:172));
else
ret=pi./(Gamma(1-z).*sin(pi.*z));
end
end
end
function ret = Gamma(z)
if isreal(z)
ret = gamma(z);
else
if real(z) >= 0
% 優(yōu)化1:預(yù)先計算常量,避免重復(fù)計算
n_terms = 50; % 優(yōu)化2:減少項數(shù),測試合適的收斂點
k = 0:n_terms;
% 優(yōu)化3:向量化計算,避免匿名函數(shù)開銷
gamma_vals = gamma(k + 1);
terms = (-1).^k ./ (gamma_vals .* (k + z));
% 優(yōu)化4:設(shè)置積分選項提高精度
options = {'RelTol', 1e-10, 'AbsTol', 1e-12};
integral_part = integral(@(x) exp(-x) .* x.^(z-1), 1, Inf, options{:});
ret = integral_part + sum(terms);
else
% 優(yōu)化5:添加輸入驗證和特殊情況處理
if abs(mod(real(z), 1)) < 1e-10 && abs(imag(z)) < 1e-10
warning('Gamma:pole', 'Gamma function has poles at non-positive integers');
ret = Inf;
else
ret = pi ./ (Gamma(1 - z) .* sin(pi .* z));
end
end
end
end
那我用deepseek優(yōu)化一下!
