# Javascript: gamma approximation

**URL:** <https://community.unix.com/t/javascript-gamma-approximation/337012>\
**Category:** Programming\
**Created:** [November 25, 2013, 6:10am UTC](https://community.unix.com/t/javascript-gamma-approximation/337012 "2013-11-25T06:10:57Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![figaro](https://community.unix.com/letter_avatar/figaro/32/6_449c533f586939b6e5f246632a46421f.png) [@figaro](https://community.unix.com/u/figaro)\
**Post date:** [November 25, 2013, 6:10am UTC](https://community.unix.com/t/javascript-gamma-approximation/337012/1 "2013-11-25T06:10:57Z")

</div>

Here is some javascript code that implements the Lanczos approximation to the gamma function ([http://en.wikipedia.org/wiki/Lanczos\_approximation\](http://en.wikipedia.org/wiki/Lanczos_approximation%5C)):

```plaintext
<script type="text/javascript">
// Gamma approximation; coefficients used by the GNU Scientific Library
function gamma(z) {
  var p = [0.99999999999980993, 676.5203681218851, -1259.1392167224028, 771.32342877765313, -176.61502916214059, 12.507343278686905, -0.13857109526572012, 9.9843695780195716e-6, 1.5056327351493116e-7];
  if z < 0.5 {
     return Math.PI / (Math.sin(Math.PI*z) * gamma(1-z));
  } else {
    z -= 1;
    x = p[0];
    for (var i = 0; i < p.length; i++) x += p/(z+i);
    t = z + p.length - 1.5;
    return Math.sqrt(2*Math.PI) * Math.pow(t, z+0.5) * Math.exp(-t) * x;
  }
}

for (var x = 0.1; x < 3; x += 0.1) document.write("x: " + x + " gamma(x): " + gamma(x) + "<br/>");
</script>

```

This returns an empty page, which usually means there is a syntactical error in the code. In the absence of a proper debugger, can anyone point out where this error might be?

Thank you in advance.

---

<div class="post-metadata">

**Author:** ![Corona688](https://community.unix.com/letter_avatar/corona688/32/6_449c533f586939b6e5f246632a46421f.png) [@Corona688](https://community.unix.com/u/Corona688)\
**Post date:** [November 25, 2013, 11:14am UTC](https://community.unix.com/t/javascript-gamma-approximation/337012/2 "2013-11-25T11:14:58Z")

</div>

If you have Firefox, ctrl-shift-j to bring up an error console. Clear it, reload the page, and you should see the error.

In this case it's complaining about missing brackets:

```nohighlight
if z < 0.5 {

```

```nohighlight
if(z < 0.5) {

```

---

<div class="post-metadata">

**Author:** ![figaro](https://community.unix.com/letter_avatar/figaro/32/6_449c533f586939b6e5f246632a46421f.png) [@figaro](https://community.unix.com/u/figaro)\
**Post date:** [November 26, 2013, 7:14am UTC](https://community.unix.com/t/javascript-gamma-approximation/337012/3 "2013-11-26T07:14:51Z")

</div>

Thank you that worked. Ctrl-Shift-J also works in Chrome.
