Kirjoittaja: tnb
Kirjoitettu: 16.10.2004 – 16.10.2004
Tagit: koodi näytille, vinkki
Vb.net tuo tullessaan tarkemmat (pidemmät) luvut, jolloin vanhojen laskentakaavojen 6-digitin laskentatarkkuus tuntuu turhan heikolta.
Onnistuin parantelemaan Gamma funktion laskentatarkkuutta vastaamaan vb.net:n doublen tarkkuutta.
Koodi käy myös esimerkiksi Rekursion käytöstä ja NaN-arvon palauttamisesta.
( Gamma funktio, kuten yleisesti tiedetään, kulkee kokonaislukujen kertomien (n-1)! kautta )
Public Shared Function Gamma(ByVal x As Double) As Double
'*********************************************************
'** Calculation of Gamma function with high accuracy **
'** Version 1.0 **
'** Visual Basic.net 2003 code **
'** x can be also negative but not 0, -1,-2...-n **
'** original from http://www.rskey.org/gamma.htm **
'** improved accuracy by TNB, 2004 **
'** key words: statistical, mathematics, algorithm **
'*********************************************************
Dim p1 As Double
'negative numbers
If x <= 0 Then
If x = Int(x) Then
Return p1.NaN : Exit Function
End If
Dim p2 As Double = Math.Sin(Math.PI * (1 - x))
p1 = Math.PI / p2 / Gamma(1 - x)
Return p1 : Exit Function
End If
'positive
Dim i As Integer
Dim xx As Double = x + 40 'the improvement
p1 = ((xx / Math.E * Math.Sqrt(xx * Math.Sinh(1 / xx) + 1 / (810 * xx ^ 6))) ^ xx) * Math.Sqrt(2 * Math.PI / xx)
For i = 0 To 39 'the improvement
p1 = p1 / (x + i)
Next
Return p1
End Function