← ppnm

Exercise "math"

Objectives

Tasks

  1. Calculate (using System.Math class) 2, 21/5, eπ, πe.

    Check that the results are correct, something like

    double sqrt2=Sqrt(2.0);
    Write($"sqrt2^2 = {sqrt2*sqrt2} (should equal 2)\n");
    

  2. Using the following Stirling approximation for the gamma-function Γ(x),

    static double gamma(double x){
    ///single precision gamma function (formula from Wikipedia)
    if(x<0)return PI/sin(PI*x)/gamma(1-x); // Euler's reflection formula
    if(x<9)return gamma(x+1)/x; // Recurrence relation
    double lngamma=x*Log(x+1/(12*x-1/x/10))-x+Log(2*PI/x)/2;
    return Exp(lngamma);
    }
    calculate Γ(1), Γ(2), Γ(3), Γ(10). Check that the results are correct (within single precision: about 6 decimal digits).

    You should put your gamma function in a static class "sfuns" (special functions) in a file "sfuns.cs", compile it separately into a library, and then link to your Main function.

  3. The gamma-function overflows very easily, so the logarithm of the gamma function, lngamma, is often a more useful function. Figure out how to modify the above formula to calculate lngamma. For simplicity you should only allow positive arguments for your lngamma:

    if(x <= 0) return double.NaN;
    if(x < 9) return lngamma(x+1) - Log(x);
    

Hints