0 Replies - 1289 Views - Last Post: 16 November 2011 - 09:01 AM

#1 Ryano121  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 1461
  • View blog
  • Posts: 3,289
  • Joined: 30-January 11

Approximate the Gamma Function

Posted 16 November 2011 - 09:01 AM

Description: See implementation in snippet.Approximate the Gamma Function using a derivative of Stirling's approximation. This method only works for values grater than zero.
using System;

namespace Gamma
{
    class Program
    {
        static void Main()
        {
            Console.WriteLine("Enter a value - ");

            // Get user input
            double input = Convert.ToDouble(Console.ReadLine());

            try
            {
                // Print Results
                Console.WriteLine("Gamma({0}) = {1}", input, Gamma(input));
                Console.WriteLine();
                Console.WriteLine("LnGamma({0}) = {1}", input, LnGamma(input));
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }

            Console.ReadLine();
        }

        // Appriximate the Natural Logarithm of the Gamma Function through
        // a derivative of Stirling's Approximation
        private static double LnGamma(double z)
        {
            // Throw exception if z is not greater than zero
            if(z <= 0)
            {
                throw new ArgumentException("Argument 'z' must be greater than zero");
            }

            // Approimate LnGamma(z)
            return 0.5 * (Math.Log(2 * Math.PI) - Math.Log(z))+ z * (Math.Log(z + 1 / (12 * z - 1 / (10 * z))) - 1);
        }

        // Approximate Gamma Function by raising e to the power of LnGamma(z),
        // which cancels the logarithm to provide Gamma(z)
        private static double Gamma(double z)
        {
            return Math.Exp(LnGamma(z));
        }
    }
}


Is This A Good Question/Topic? 0
  • +

Page 1 of 1