BCSL-058 (Computer oriented Numerical techniques Lab )

     BCSL-058 Computer oriented Numerical techniques Lab  (Assignments Solution)

    Course Code                        :            BCSL-058

    Course Title                         :            Computer oriented Numerical techniques Lab

    Assignment Number            :           BCA(V)051/Assignment/2024-25 

    Maximum Marks                 :             50

    Weightage                            :            25% 

    Last Date of Submission      :           31stOctober,2024(For July, Session) 

                                                               30thApril, 2025(For January, Session)


Q1. Write a program in C that accepts a decimal number and displays its floating-point equivalent number. You may make assumptions to simplify theprogram, however, yourrepresentation of floating point number should becloser to IEEE 754 standard 32 bit representation.

Ans. C Program to Convert Decimal to IEEE 754 Floating Point

#include <stdio.h>

#include <stdint.h>

#include <string.h>


typedef union {

    float f;

    uint32_t i;

} FloatUnion;


void printIEEE754(float number) {

    FloatUnion u;

    u.f = number;


    // Extract the sign, exponent, and mantissa

    uint32_t sign = (u.i >> 31) & 0x1;

    uint32_t exponent = (u.i >> 23) & 0xFF;

    uint32_t mantissa = u.i & 0x7FFFFF;


    // Print the results

    printf("IEEE 754 Representation:\n");

    printf("Sign: %u\n", sign);

    printf("Exponent: %u\n", exponent);

    printf("Mantissa: %u\n", mantissa);

}


int main() {

    float decimalNumber;


    // Input: Get the decimal number from the user

    printf("Enter a decimal number: ");

    scanf("%f", &decimalNumber);


    // Display its floating-point equivalent in IEEE 754 representation

    printIEEE754(decimalNumber);


    return 0;

}

Explanation of the Code:

  1. Union Definition: A union FloatUnion is defined to hold both a float and its corresponding unsigned integer representation.
  2. Input Handling: The program prompts the user to enter a decimal number.
  3. Conversion to IEEE 754:
    • The float is converted to its binary representation using the union.
    • The sign bit is extracted using bit manipulation.
    • The exponent and mantissa are also extracted using bit shifts and masks.
  4. Output: The program prints the sign, exponent, and mantissa.

How to Compile and Run:

  1. Save the code to a file named decimal_to_ieee754.c.
  2. Open a terminal and navigate to the directory where the file is saved.
  3. Compile the program using:
    gcc decimal_to_ieee754.c -o decimal_to_ieee754
  4. Run the program.
    ./decimal_to_ieee754
Q2. Write a program in C to implement Gauss Seidel method for finding the roots oflinear equations
Ans.

C Program to Implement the Gauss-Seidel Method

c

#include <stdio.h> #include <math.h> #define MAX 100 #define EPSILON 0.00001 void gaussSeidel(double a[MAX][MAX], double b[MAX], double x[MAX], int n) { double oldX[MAX]; int i, j; for (i = 0; i < n; i++) { x[i] = 0.0; // Initialize solution vector } int iterations = 0; do { for (i = 0; i < n; i++) { oldX[i] = x[i]; // Store the old value of x[i] double sum = 0.0; for (j = 0; j < n; j++) { if (j != i) { sum += a[i][j] * x[j]; } } x[i] = (b[i] - sum) / a[i][i]; // Update x[i] } iterations++; // Check for convergence double maxDiff = 0.0; for (i = 0; i < n; i++) { maxDiff = fmax(maxDiff, fabs(x[i] - oldX[i])); } if (maxDiff < EPSILON) { break; // Convergence achieved } } while (1); printf("Converged in %d iterations.\n", iterations); } int main() { double a[MAX][MAX], b[MAX], x[MAX]; int n, i, j; // Input: Get the number of equations printf("Enter the number of equations: "); scanf("%d", &n); // Input: Get the coefficients of the equations printf("Enter the augmented matrix coefficients (A):\n"); for (i = 0; i < n; i++) { for (j = 0; j < n; j++) { scanf("%lf", &a[i][j]); } } // Input: Get the constants printf("Enter the constants (B):\n"); for (i = 0; i < n; i++) { scanf("%lf", &b[i]); } // Call the Gauss-Seidel method gaussSeidel(a, b, x, n); // Output: Display the solution printf("The solution is:\n"); for (i = 0; i < n; i++) { printf("x[%d] = %.6lf\n", i, x[i]); } return 0; }

Explanation of the Code:

  1. Definitions: Constants are defined for maximum size and convergence criteria.
  2. Function: The gaussSeidel function performs the iterative process of updating the solution vector x.
    • It initializes the solution vector to zero.
    • It repeatedly updates each variable based on the latest values of the other variables until the difference between iterations is below a specified threshold (EPSILON).
  3. Input Handling: The program prompts the user to enter the number of equations and their coefficients.
  4. Output: It prints the number of iterations taken to converge and the solution for each variable.

How to Compile and Run:

  1. Save the code to a file named gauss_seidel.c.
  2. Open a terminal and navigate to the directory where the file is saved.
  3. Compile the program using:

    gcc gauss_seidel.c -o gauss_seidel -lm
  4. Run the program:
    ./gauss_seidel

Example Usage:

For a system of equations like:

  1. 4x1x2+x3=74x_1 - x_2 + x_3 = 7
  2. x1+3x2+2x3=14-x_1 + 3x_2 + 2x_3 = 14
  3. 2x12x2+4x3=282x_1 - 2x_2 + 4x_3 = 28

The user would input the coefficients as a matrix and the corresponding constants to find the values of x1,x2,x_1, x_2, and x3x_3.

Q3. Write a program in C to implement Bisection method for finding a positive rootof the equation X2 - 9x + 21 = 0. You have to make suitable choice for thebounds. 

Ans.

C Program to Implement the Bisection Method

c

#include <stdio.h> #include <math.h> // Define the function f(x) double f(double x) { return x * x - 9 * x + 21; // x^2 - 9x + 21 } // Bisection method function void bisection(double a, double b, double tolerance) { if (f(a) * f(b) >= 0) { printf("Bisection method fails: f(a) and f(b) must have different signs.\n"); return; } double c; int iterations = 0; while ((b - a) >= tolerance) { // Find the midpoint c = (a + b) / 2; // Check if c is the root or if the tolerance level is met if (f(c) == 0.0) { break; // c is the root } else if (f(c) * f(a) < 0) { b = c; // The root lies in the left subinterval } else { a = c; // The root lies in the right subinterval } iterations++; } printf("Root found: %.6lf\n", c); printf("Number of iterations: %d\n", iterations); } int main() { double a = 0; // Lower bound double b = 10; // Upper bound double tolerance = 0.00001; // Tolerance level printf("Finding the root of the equation x^2 - 9x + 21 = 0 using Bisection Method\n"); printf("Initial bounds: [%.2lf, %.2lf]\n", a, b); bisection(a, b, tolerance); return 0; }

Explanation of the Code:

  1. Function Definition: The function f(double x) defines the equation x29x+21x^2 - 9x + 21.
  2. Bisection Method:
    • The bisection function checks if the function values at the bounds a and b have opposite signs, which is necessary for the method to work.
    • It then calculates the midpoint and updates the bounds based on where the root lies.
    • The process continues until the interval is less than the specified tolerance.
  3. Input Handling: The program sets initial bounds and tolerance.
  4. Output: It prints the found root and the number of iterations taken to reach that root.

How to Compile and Run:

  1. Save the code to a file named bisection_method.c.
  2. Open a terminal and navigate to the directory where the file is saved.
  3. Compile the program using:
    gcc bisection_method.c -o bisection_method -lm
  4. Run the program:
    ./bisection_method

Example Output:

When you run the program, it will display the found root of the equation and the number of iterations it took to find it. Given the function, the expected positive root is approximately x=3x = 3 (since 3293+21=03^2 - 9*3 + 21 = 0).

Q4. Write a program in C for the demonstration of Newton's BackwardInterpolation Formula. 

Ans.

C Program for Newton's Backward Interpolation Formula

c

#include <stdio.h> #define MAX 100 // Function to calculate the backward difference table void backwardDifferenceTable(double x[], double y[], double diff[MAX][MAX], int n) { // Initialize the first column of the difference table for (int i = 0; i < n; i++) { diff[i][0] = y[i]; } // Calculate the backward differences for (int j = 1; j < n; j++) { for (int i = 0; i < n - j; i++) { diff[i][j] = diff[i][j - 1] - diff[i + 1][j - 1]; } } } // Function to perform backward interpolation double backwardInterpolation(double x[], double y[], double value, int n) { double diff[MAX][MAX]; backwardDifferenceTable(x, y, diff, n); double h = x[1] - x[0]; // Assuming uniform spacing int k = (int)((value - x[0]) / h); // Determine the index for interpolation double result = diff[k][0]; // Start with the first term of the result // Calculate the result using the backward interpolation formula double term = 1; // Term for backward differences for (int j = 1; j <= k; j++) { term *= (value - x[k - j]) / h; // (x - x[k-j]) / h result += (term * diff[k - j][j]); // Add the term to the result } return result; } int main() { double x[MAX], y[MAX]; int n; // Input: Number of data points printf("Enter the number of data points: "); scanf("%d", &n); // Input: Data points printf("Enter the x values:\n"); for (int i = 0; i < n; i++) { scanf("%lf", &x[i]); } printf("Enter the corresponding y values:\n"); for (int i = 0; i < n; i++) { scanf("%lf", &y[i]); } // Input: Value to interpolate double value; printf("Enter the value to interpolate: "); scanf("%lf", &value); // Perform interpolation and display the result double result = backwardInterpolation(x, y, value, n); printf("The interpolated value at x = %.2lf is: %.6lf\n", value, result); return 0; }

Explanation of the Code:

  1. Backward Difference Table: The function backwardDifferenceTable fills a table with backward differences based on the provided yy values.

    • The first column of the table is filled with yy values.
    • The subsequent columns are calculated using backward differences.
  2. Backward Interpolation: The function backwardInterpolation uses the backward difference table to calculate the interpolated value for a given xx using the backward interpolation formula:

    P(x)=yk+(xxk)hΔyk+(xxk)(xxk1)2!h2Δ2yk+P(x) = y_k + \frac{(x - x_k)}{h} \Delta y_k + \frac{(x - x_k)(x - x_{k-1})}{2!h^2} \Delta^2 y_k + \cdots
    • It calculates the term using the backward differences and accumulates the result.
  3. Input Handling: The program prompts the user for the number of data points, the xx and yy values, and the value to interpolate.

  4. Output: The program displays the interpolated value.

Q5. Write program in C for the demonstration of Bessel's Formula. 
Ans.

C Program to Demonstrate Bessel's Formula

c

#include <stdio.h> // Function to calculate factorial double factorial(int n) { if (n == 0 || n == 1) { return 1.0; } double fact = 1.0; for (int i = 2; i <= n; i++) { fact *= i; } return fact; } // Function to calculate Bessel function J0(x) double besselJ0(double x) { double sum = 0.0; for (int k = 0; k < 100; k++) { // 100 terms for sufficient accuracy double term = (pow(-1, k) * pow(x / 2, 2 * k)) / (factorial(k) * factorial(k)); sum += term; } return sum; } int main() { double x; // Input: Get the value of x from the user printf("Enter the value of x to compute J0(x): "); scanf("%lf", &x); // Calculate Bessel function J0(x) double result = besselJ0(x); // Output: Display the result printf("The Bessel function J0(%.2lf) is approximately: %.6lf\n", x, result); return 0; }

Explanation of the Code:

  1. Factorial Function: The factorial function computes the factorial of a given integer nn.
  2. Bessel Function Calculation:
    • The besselJ0 function computes the Bessel function J0(x)J_0(x) using its series expansion.
    • A loop runs for a fixed number of terms (100 in this case) to accumulate the series sum. This should provide sufficient accuracy for typical values of xx.
  3. Input Handling: The program prompts the user to input a value for xx.
  4. Output: It calculates and displays the Bessel function J0(x)J_0(x).
Q6. Write a program in C to demonstrate theNewton's Divided DifferenceMethod. 
Ans.

The divided difference method computes coefficients of the interpolating polynomial based on the given data points. The polynomial is constructed in the form:

P(x)=y0+(xx0)f[x0,x1]1!+(xx0)(xx1)f[x0,x1,x2]2!+P(x) = y_0 + (x - x_0) \frac{f[x_0, x_1]}{1!} + (x - x_0)(x - x_1) \frac{f[x_0, x_1, x_2]}{2!} + \ldots

C Program for Newton's Divided Difference Method

c

#include <stdio.h> #define MAX 100 // Function to calculate divided differences void dividedDifference(double x[], double y[], double diff[MAX][MAX], int n) { // Initialize the first column with y values for (int i = 0; i < n; i++) { diff[i][0] = y[i]; } // Calculate divided differences for (int j = 1; j < n; j++) { for (int i = 0; i < n - j; i++) { diff[i][j] = (diff[i + 1][j - 1] - diff[i][j - 1]) / (x[i + j] - x[i]); } } } // Function to perform polynomial interpolation using Newton's Divided Difference double newtonInterpolation(double x[], double y[], double value, int n) { double diff[MAX][MAX]; dividedDifference(x, y, diff, n); double result = diff[0][0]; // Start with the first term of the polynomial double term; // Term to be added to the result for (int i = 1; i < n; i++) { term = diff[0][i]; // Start with the next divided difference for (int j = 0; j < i; j++) { term *= (value - x[j]); // Multiply by (x - x[j]) } result += term; // Add the term to the result } return result; } int main() { double x[MAX], y[MAX]; int n; // Input: Get the number of data points printf("Enter the number of data points: "); scanf("%d", &n); // Input: Get x values printf("Enter the x values:\n"); for (int i = 0; i < n; i++) { scanf("%lf", &x[i]); } // Input: Get y values printf("Enter the corresponding y values:\n"); for (int i = 0; i < n; i++) { scanf("%lf", &y[i]); } // Input: Get the value to interpolate double value; printf("Enter the value to interpolate: "); scanf("%lf", &value); // Perform interpolation and display the result double result = newtonInterpolation(x, y, value, n); printf("The interpolated value at x = %.2lf is: %.6lf\n", value, result); return 0; }

Explanation of the Code:

  1. Divided Difference Calculation:

    • The dividedDifference function creates a table of divided differences based on the given yy values.
    • It initializes the first column with the yy values and computes the rest of the table using the divided difference formula.
  2. Newton Interpolation:

    • The newtonInterpolation function computes the polynomial value at the given input value using the divided differences calculated previously.
    • It constructs the polynomial iteratively by multiplying the necessary terms.
  3. Input Handling:

    • The program prompts the user for the number of data points, the xx values, and the corresponding yy values.
    • The value at which to interpolate is also inputted.
  4. Output:

    • The program calculates and prints the interpolated value.

How to Compile and Run:

  1. Save the code to a file named newton_divided_difference.c.
  2. Open a terminal and navigate to the directory where the file is saved.
  3. Compile the program using:

    gcc newton_divided_difference.c -o newton_divided_difference -lm
  4. Run the program:

    ./newton_divided_difference

Example Usage:

When prompted, you can input data points like:

  • x:[1,2,3,4]x: [1, 2, 3, 4]
  • y:[1,4,9,16]y: [1, 4, 9, 16]

And if you want to interpolate the value at x=2.5x = 2.5, the program will calculate and print the interpolated value based on the provided data points.

Q7. Write a program in C to find the approximate value of the following definiteintegral usingSimpson's 1/3 rule: ∫ 𝑡𝑎𝑛 𝑥 𝑑𝑥 𝜋 4 0

Ans.

Simpson's 1/3 Rule

Simpson's 1/3 Rule is a numerical method for approximating the definite integral of a function. It works by dividing the interval into an even number of subintervals and approximating the area under the curve with parabolic segments.

The formula for Simpson's 1/3 Rule is given by:

abf(x)dxh3[f(a)+4i=1n/2f(x2i1)+2i=1n/21f(x2i)+f(b)]\int_{a}^{b} f(x) \, dx \approx \frac{h}{3} \left[ f(a) + 4 \sum_{i=1}^{n/2} f(x_{2i-1}) + 2 \sum_{i=1}^{n/2-1} f(x_{2i}) + f(b) \right]

Where:

  • h=banh = \frac{b-a}{n} (the width of each subinterval)
  • nn is the number of subintervals (must be even)
  • xix_i are the points in the interval

C Program to Approximate the Definite Integral

c

#include <stdio.h> #include <math.h> // Function to compute the integrand double f(double x) { return tan(x); } // Function to implement Simpson's 1/3 Rule double simpsonsRule(double a, double b, int n) { // Check if n is even if (n % 2 != 0) { printf("n must be an even number.\n"); return -1; } double h = (b - a) / n; // Width of each subinterval double sum = f(a) + f(b); // f(a) + f(b) // Sum the odd indexed terms (4 * f(x_{2i-1})) for (int i = 1; i < n; i += 2) { sum += 4 * f(a + i * h); } // Sum the even indexed terms (2 * f(x_{2i})) for (int i = 2; i < n - 1; i += 2) { sum += 2 * f(a + i * h); } return (h / 3) * sum; // Final approximation } int main() { double a = 0.0; // Lower limit double b = M_PI / 4; // Upper limit (π/4) int n = 10; // Number of subintervals (must be even) // Calculate the approximate value of the integral double result = simpsonsRule(a, b, n); // Output the result if (result != -1) { printf("The approximate value of the integral ∫ tan(x) dx from 0 to π/4 is: %.6lf\n", result); } return 0; }

Explanation of the Code:

  1. Function Definition:
    • The function f(double x) computes the value of tan(x)\tan(x), which is the integrand.
  2. Simpson's Rule Implementation:
    • The function simpsonsRule(double a, double b, int n) calculates the integral using Simpson's 1/3 Rule.
    • It checks if nn is even; if not, it prompts an error.
    • It computes the width of the subintervals, sums the contributions from the endpoints, odd, and even indexed points based on the formula.
  3. Main Function:
    • It defines the limits of integration aa and bb, and sets the number of subintervals nn (which must be even).
    • It calls simpsonsRule and prints the result.

How to Compile and Run:

  1. Save the code to a file named simpsons_rule.c.
  2. Open a terminal and navigate to the directory where the file is saved.
  3. Compile the program using:
    gcc simpsons_rule.c -o simpsons_rule -lm
  4. Run the program:
    ./simpsons_rule

Example Output:

When you run the program, it will calculate and print the approximate value of the integral 0π4tan(x)dx\int_{0}^{\frac{\pi}{4}} \tan(x) \, dx. The result should be approximately ln(2)0.693147\ln(2) \approx 0.693147 since the integral of tan(x)\tan(x) from 00 to π4\frac{\pi}{4} equals ln(2)\ln(2).

  #CODEWITHCHIRAYU

                                                              Thank You 😊                                                            

Comments

Popular posts from this blog

IGNOU Term End December2024 Exam Result

Top 12 (Most Impotant Questions) BCS-051 : INTRODUCTION TO SOFTWARE

COMPANY SECRETARIES EXAMINATION – CS Examination Admit Cards