如何创建一个函数来计算带小数的数字的阶乘? [英] How to make a function that computes the factorial for numbers with decimals?

查看:168
本文介绍了如何创建一个函数来计算带小数的数字的阶乘?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何制作计算小数的阶乘(或伽玛函数)的函数JavaScript中的数字?例如,我怎么能计算 2.33!

How can I make a function that calculates the factorial (or the gamma function) of decimal numbers in JavaScript? For example, how could I calculate 2.33!?

推荐答案

我可能找到了现有的解决方案......
这是Lanczos方法的一个实现,我在瑞典维基百科上找到了它( http:/ /sv.wikipedia.org/wiki/Gammafunktionen )。它是用python编写的,并且说正确最多15位小数。我将它移植到js,交叉检查一些随机值( http://www.efunda.com/math/gamma /findgamma.cfm )。

I might have found an existing solution... It's an implementation of Lanczos method, I found it at the swedish wikipedia (http://sv.wikipedia.org/wiki/Gammafunktionen). It was written in python and says to be correct up to 15 decimals. I ported it to js, cross checked some random values against (http://www.efunda.com/math/gamma/findgamma.cfm).

http://jsfiddle.net/ Fzy9C /

var g = 7;
var C = [0.99999999999980993, 676.5203681218851, -1259.1392167224028,771.32342877765313, -176.61502916214059, 12.507343278686905, -0.13857109526572012, 9.9843695780195716e-6, 1.5056327351493116e-7];

function gamma(z) {

    if (z < 0.5) return Math.PI / (Math.sin(Math.PI * z) * gamma(1 - z));
    else {
        z -= 1;

        var x = C[0];
        for (var i = 1; i < g + 2; i++)
        x += C[i] / (z + i);

        var t = z + g + 0.5;
        return Math.sqrt(2 * Math.PI) * Math.pow(t, (z + 0.5)) * Math.exp(-t) * x;
    }
}

(当然它不支持虚数,因为js没有)

(and ofcourse it does not support imaginary numbers, since js does not)

这篇关于如何创建一个函数来计算带小数的数字的阶乘?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆