gurkensaas
gurkensaas

Reputation: 913

Why is my approximation of the Gamma function not exact?

So I'm setting out to recreating some math functions from the math library from python.

One of those functions is the math.gamma-function. Since I know my way around JavaScript I thought I might try to translate the JavaScript implementation of the Lanczos approximation on Rosetta code into Applescript code:

on gamma(x)
    set p to {1.0, 676.520368121885, -1259.139216722403, 771.323428777653, -176.615029162141, 12.507343278687, -0.138571095266, 9.98436957801957E-6, 1.50563273514931E-7}
    set E to 2.718281828459045
    set g to 7
    if x < 0.5 then
        return pi / (sin(pi * x) * (gamma(1 - x)))
    end if
    set x to x - 1
    set a to item 1 of p
    set t to x + g + 0.5
    repeat with i from 2 to count of p
        set a to a + ((item i of p) / (x + i))
    end repeat
    return ((2 * pi) ^ 0.5) * (t ^ x + 0.5) * (E ^ -t) * a
end gamma

The required function for this to run is:

on sin(x)
    return (do shell script "python3 -c 'import math; print(math.sin(" & x & "))'") as number
end sin

All the other functions of the Javascript implementation have been removed to not have too many required functions, but the inline operations I introduced produce the same result.


This Javascript-code works great when trying to run it in the browser-console, but my Applescript implementation doesn't produce answers anywhere near the actual result. Is it because...

Upvotes: 0

Views: 203

Answers (1)

htmlcat
htmlcat

Reputation: 336

You made two mistakes in your code:

First of all, the i in your repeat statement starts at 2 rather than 1, which is fine for (item i of p), but it needs to be subtracted by 1 in the (x + i).

Secondly, in the code (t ^ x + 0.5) in the return statement, the t and x are being calculated first since they are exponents and then added to 0.5, but according to the JavaScript implementation the x and 0.5 need to be added together first instead.

Upvotes: 2

Related Questions