The following task demonstrates the truncation error while computing a famous factorial function,

Question

The following task demonstrates the truncation error while computing a famous factorial function, There is a famous numerical approximate formula for n

n! = (-)” √2mn

where e is Euler’s number and n is pi

1. Write a C

2. program to output a table with the following format.

3. Use the predefined value for pland e in your IDE

Sample Output:

Enter a number to calculate its factorial: 10

n n! approximation Absolute Error Relative Error
1 1 0.922137 0.077863 0.077863
2 2 1.919004 0.080996 0.040498
3 6 5.836210 0.163790 0.027298
4 24 23.506175 0493825 0.020576
5 120 118.019168 1.980832 0.016507
6 720 710.078185 9.921815 0.013780
7 5040 4980.395832 59.604168 0.011826
8 40320 39902.395453 417.604547 0.010357
9 362880 359536.872842 3343.127158 0.009213
10 3628800 3598695.618741 30104.381259 0.008296

 

Explanation

The actual factorial calculation is given in the question. The product of all the numbers from 1 to that number, i.e.,
n! = n* (n-1) *(n-2)  ……1

is a simple way to calculate factorial.
n!= (n/e)n (2 (pi)n) is the exact formula for calculating factorial.
As a result, we create two methods to calculate factorial using the trivial technique and the accurate method.
The absolute inaccuracy is calculated by multiplying the approximate fact by the actual fact.
The relative error is calculated using the formula: abs error/approximate fact.

Code

#include<conio.h>
#include<stdio.h>
#include<math.h>

//function declaration
long int fact(int n);
float exactFact(int n);

//main function
void main()
{
    //variable declaration
    int n,i;
    long int fac;
    float eFac, absError, relError;
    
    //user input for value of n
    printf("\nEnter a number to find its factorial: ");
    scanf("%d",&n);
    printf("\nNumber\tFac\tApprox\t\tAbsError\tRelativeError");
    //loop to calculate values
    for(i=1; i<=n; i++)
    {	fac=fact(i);
        eFac=exactFact(i);
        //calculate error
        absError=fac-eFac;
        relError=absError/fac;
        printf("\n%d\t%ld\t%f\t%f\t%f",i,fac,eFac,absError,relError);
    }
}

//function definition to calculate approximate factorial
long int fact(int n)
{	long int f=1;
    long int i;
    for(i=1; i<=n; i++)
        f=f*i;
    return f;
}

//function to calculate exact factorial
float exactFact(int n)
{	float f;
    
    float num= n/M_E;
    
    f= pow(num,n) * pow((2*M_PI*n),0.5);
    return f;
}

Output

 famous factorial function

 

Also read, For these situations, just design the h files you need to implement the classes you’d need.

 

Share this post

Leave a Reply

Your email address will not be published. Required fields are marked *