← ppnm

Exercise "math"

Objectives

Tasks

  1. Calculate using C# System.Math class [C++ <cmath> header] 2, 21/5, eπ, πe.

    Something like

    double sqrt2=System.Math.Sqrt(2.0);
    System.Console.WriteLine($"Sqrt(2) = {sqrt2}");
    
    double sqrt2=std::sqrt(2.0);
    std::cout << "sqrt(2) = " << sqrt2 << std::endl;
    

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

    using static System.Math;
    public static class sfuns{
    public static double fgamma(double x){ ///single precision gamma function
    	if(x<0)return PI/Sin(PI*x)/fgamma(1-x); // Euler's reflection formula
    	if(x<9)return fgamma(x+1)/x; // Recurrence relation
    	double lnfgamma=x*Log(x+1/(12*x-1/x/10))-x+Log(2*PI/x)/2;
    	return Exp(lnfgamma);
    	}
    }
    #include<cmath>
    #include"sfuns.h"
    namespace sfuns{
    double fgamma(double x){
    	if(x<0)return M_PI/std::sin(M_PI*x)/fgamma(1-x);
    	if(x<9)return fgamma(x+1)/x;
    	double lnfgamma=x*std::log(x+1/(12*x-1/x/10))-x+std::log(2*PI/x)/2;
    	return std::exp(lnfgamma);
    	}
    }
    // "sfuns.h" header file
    #ifndef HAVE_SFUNS_H
    #define HAVE_SFUNS_H
    namespace sfuns{
    double fgamma(double x);
    }
    #endif
    
    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" [namespace "sfuns"] in a file "sfuns.cs" ["sfuns.cc"], compile it separately into a library "sfuns.dll" [object code "sfuns.o"], and then link to your Main [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);
    
    if(x <= 0) return NAN;
    if(x < 9) return lngamma(x+1) - std::log(x);
    

Hints