成人在线

官方gamma函数没有复数,于是自己写了一个没有优化的

标签: 科学计算

石雨泽 2025-05-27 22:19:16

以下,就是通过定义式得来的复数域gamma函数,未使用近似算:

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


861 1 3 收藏 回复

回复

HanqinWu 2025-10-10 #1

function ret = Gamma(z)

    if isreal(z)

        ret = gamma(z);

    else

        if real(z) >= 0

            % 优化1:预先计算常量,避免重复计算

            n_terms = 50;  % 优化2:减少项数,测试合适的收敛点

            k = 0:n_terms;

            

            % 优化3:向量化计算,避免匿名函数开销

            gamma_vals = gamma(k + 1);

            terms = (-1).^k ./ (gamma_vals .* (k + z));

            

            % 优化4:设置积分选项提高精度

            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

            % 优化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优化一下!