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:
- Union Definition: A union
FloatUnion
is defined to hold both a float and its corresponding unsigned integer representation. - Input Handling: The program prompts the user to enter a decimal number.
- 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.
- Output: The program prints the sign, exponent, and mantissa.
How to Compile and Run:
- Save the code to a file named
decimal_to_ieee754.c
. - Open a terminal and navigate to the directory where the file is saved.
- Compile the program using:
gcc decimal_to_ieee754.c -o decimal_to_ieee754
- Run the program.
./decimal_to_ieee754
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:
- Definitions: Constants are defined for maximum size and convergence criteria.
- Function: The
gaussSeidel
function performs the iterative process of updating the solution vectorx
.- 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
).
- Input Handling: The program prompts the user to enter the number of equations and their coefficients.
- Output: It prints the number of iterations taken to converge and the solution for each variable.
How to Compile and Run:
- Save the code to a file named
gauss_seidel.c
. - Open a terminal and navigate to the directory where the file is saved.
- Compile the program using:
gcc gauss_seidel.c -o gauss_seidel -lm
- Run the program:
./gauss_seidel
Example Usage:
For a system of equations like:
The user would input the coefficients as a matrix and the corresponding constants to find the values of and .
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:
- Function Definition: The function
f(double x)
defines the equation . - Bisection Method:
- The
bisection
function checks if the function values at the boundsa
andb
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.
- The
- Input Handling: The program sets initial bounds and tolerance.
- Output: It prints the found root and the number of iterations taken to reach that root.
How to Compile and Run:
- Save the code to a file named
bisection_method.c
. - Open a terminal and navigate to the directory where the file is saved.
- Compile the program using:
gcc bisection_method.c -o bisection_method -lm
- 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 (since ).
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:
Backward Difference Table: The function
backwardDifferenceTable
fills a table with backward differences based on the provided values.- The first column of the table is filled with values.
- The subsequent columns are calculated using backward differences.
Backward Interpolation: The function
backwardInterpolation
uses the backward difference table to calculate the interpolated value for a given using the backward interpolation formula:- It calculates the term using the backward differences and accumulates the result.
Input Handling: The program prompts the user for the number of data points, the and values, and the value to interpolate.
Output: The program displays the interpolated value.
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:
- Factorial Function: The
factorial
function computes the factorial of a given integer . - Bessel Function Calculation:
- The
besselJ0
function computes the Bessel function 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 .
- The
- Input Handling: The program prompts the user to input a value for .
- Output: It calculates and displays the Bessel function .
The divided difference method computes coefficients of the interpolating polynomial based on the given data points. The polynomial is constructed in the form:
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:
Divided Difference Calculation:
- The
dividedDifference
function creates a table of divided differences based on the given values. - It initializes the first column with the values and computes the rest of the table using the divided difference formula.
- The
Newton Interpolation:
- The
newtonInterpolation
function computes the polynomial value at the given inputvalue
using the divided differences calculated previously. - It constructs the polynomial iteratively by multiplying the necessary terms.
- The
Input Handling:
- The program prompts the user for the number of data points, the values, and the corresponding values.
- The value at which to interpolate is also inputted.
Output:
- The program calculates and prints the interpolated value.
How to Compile and Run:
- Save the code to a file named
newton_divided_difference.c
. - Open a terminal and navigate to the directory where the file is saved.
- Compile the program using:
gcc newton_divided_difference.c -o newton_divided_difference -lm
- Run the program:
./newton_divided_difference
Example Usage:
When prompted, you can input data points like:
And if you want to interpolate the value at , 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:
Where:
- (the width of each subinterval)
- is the number of subintervals (must be even)
- 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:
- Function Definition:
- The function
f(double x)
computes the value of , which is the integrand.
- The function
- 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 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.
- The function
- Main Function:
- It defines the limits of integration and , and sets the number of subintervals (which must be even).
- It calls
simpsonsRule
and prints the result.
How to Compile and Run:
- Save the code to a file named
simpsons_rule.c
. - Open a terminal and navigate to the directory where the file is saved.
- Compile the program using:
gcc simpsons_rule.c -o simpsons_rule -lm
- Run the program:
./simpsons_rule
Example Output:
When you run the program, it will calculate and print the approximate value of the integral . The result should be approximately since the integral of from to equals .
#CODEWITHCHIRAYUThank You 😊
Comments
Post a Comment