Connecting Tech Pros Worldwide Forums | Help | Site Map

Factorial and Gamma Functions for VB

kadghar's Avatar
Expert
 
Join Date: Apr 2007
Location: Mexico City
Posts: 1,155
#1   Jun 14 '07
Hi, I saw that Killer posted a simple Factorial Function that allows you to calculate up to 13!, well, you can use this for bigger numbers by changing the variable type.

Why is this?

You can use factorial on integers (that should be the input), the output could be a string or a double, anyway you will alwas have the factorial. The only restriction is in the input.

Yes, i mean this function works fine for values up to 170! or something like that:

Expand|Select|Wrap|Line Numbers
  1. Public Function Factorial(ByVal bNum As Integer) As Double
  2.   Dim I As Double
  3.   If bNum <= 0 Then Exit Function
  4.   Factorial = 1
  5.   For I = 1 To bNum
  6.     Factorial = Factorial * I
  7.   Next
  8. End Function
Also VB can be used for making a little bit more complex functions like a Gamma.

What is a Gamma?

A Gamma Function is the generalization of the Factorial Function (this means you can use any positive number in it). If you use a Gamma for an integer, it'll give you the Factorial of the previus integer. i.e.:

G(5) = 4 ! = 24

The advantage is that even if you cannot have 4.25 ! , you can always have
G(5.25) = 35.2088612458766

Cool!!!

To obtain it, you can use many numerical methods. Here I used an old friend by Euler-Mascheroni.

Expand|Select|Wrap|Line Numbers
  1. Public Function Gamma(ByVal Dou1 As Double) As Double
  2.     Dim I As Integer
  3.     Dim Dou2 As Double
  4.     Dim Dou3 As Double
  5.  
  6.     If Fix(Dou1) = Dou1 Then
  7.         If Dou1 = 0 Or Dou1 = 1 Then
  8.             Gamma = 1
  9.             Exit Function
  10.         Else
  11.             Dou2 = 1
  12.             For I = 1 To Dou1 - 1
  13.                 Dou2 = Dou2 * I
  14.             Next
  15.             Gamma = Dou2
  16.             Exit Function
  17.         End If
  18.     ElseIf Dou1 > 3 Then
  19.         Dou2 = 1
  20.         For I = 1 To (Fix(Dou1) - 1)
  21.             Dou2 = Dou2 * (Dou1 - 1)
  22.             Dou1 = Dou1 - 1
  23.         Next
  24.         Dou3 = Exp(-0.57721566 * Dou1) / Dou1
  25.         For I = 1 To 9999
  26.             Dou3 = Dou3 * ((1 + (Dou1 / I)) ^ (-1)) * Exp(Dou1 / I)
  27.         Next
  28.         Dou3 = Dou2 * Dou3
  29.         Gamma = Dou3
  30.     Else
  31.         Dou3 = Exp(-0.577215664901533 * Dou1) / Dou1
  32.         For I = 1 To 9999
  33.             Dou3 = Dou3 * ((1 + (Dou1 / I)) ^ (-1)) * Exp(Dou1 / I)
  34.         Next
  35.         Gamma = Dou3
  36.     End If
  37. End Function
I hope this could be of some use next time you're dealing with someones homework.

Kad



Closed Thread