INDEX
PAGE REMAR
S.NO DATE NAME OF THE PRACTICAL NO. KS
Practical -1
1.Write a program Regula falsi method using while loop
Program:
#include<stdio.h>
#include<conio.h>
#include<math.h>
/* Defining equation to be solved.
Change this equation to solve another problem. */
#define f(x) x*log10(x) - 1.2
int main()
{
float x0, x1, x2, f0, f1, f2, e;
int step = 1;
clrscr();
/* Inputs */
up:
printf("\nEnter two initial guesses:\n");
scanf("%f%f", &x0, &x1);
printf("Enter tolerable error:\n");
scanf("%f", &e);
/* Calculating Functional Values */
f0 = f(x0);
f1 = f(x1);
/* Checking whether given guesses brackets the root or not. */
if( f0*f1 > 0.0)
{
printf("Incorrect Initial Guesses.\n");
goto up;
}
/* Implementing Regula Falsi or False Position Method */
printf("\nStep\t\tx0\t\tx1\t\tx2\t\tf(x2)\n");
do
{
x2 = x0 - (x0-x1) * f0/(f0-f1);
f2 = f(x2);
printf("%d\t\t%f\t%f\t%f\t%f\n",step, x0, x1, x2, f2);
if(f0*f2 < 0)
{
x1 = x2;
f1 = f2;
}
else
{
x0 = x2;
f0 = f2;
}
step = step + 1;
}while(fabs(f2)>e);
printf("\nRoot is: %f", x2);
getch();
return 0;
}
Output:
Enter two initial guesses:
2
3
Enter tolerable error:
0.000001
Step x0 x1 x2 f(x2)
1 2.000000 3.000000 2.721014 -0.017091
2 2.721014 3.000000 2.740206 -0.000384
3 2.740206 3.000000 2.740636 -0.000009
4 2.740636 3.000000 2.740646 -0.000000
Root is: 2.740646
Practical -2
2. write a program for iterative methods using while loop
Program:
#include <stdio.h>
int main()
{
// For Loop
for (int i = 0; i < 5; i++) {
printf("%d ", i);
}
printf("\n");
// While Loop
int count = 0;
while (count < 5) {
printf("%d ", count);
count++;
}
printf("\n");
// Do-While Loop
count = 0;
do {
printf("%d ", count);
count++;
} while (count < 5);
printf("\n");
return 0;
}
Output
0 1 2 3 4
0 1 2 3 4
0 1 2 3 4
Practical -3
Algorithm to fit a straight line y = ax + b to given
set of data points:
1. Start
2. Find number of pairs of data points (n) to be fitted
3. Input the x values and y values.
Σ Σ Σ Σ
4. Find x, y, x2 and xy
5. Solve the system of equations given by (1) and (2) using
matrix method, where
C = A−1B
6. Required line of best fit is y = ax + b
7. Stop
Flow Chart for fitting a straight line to given set of data points
3. Write a program to fit a Straight Y=a+bx
#include<stdio.h>
#include<conio.h>
#define S 50
int main()
{
int n, i;
float x[S], y[S], sumX=0, sumX2=0, sumY=0, sumXY=0, a, b;
clrscr();
/* Input */
printf("How many data points?\n");
scanf("%d", &n);
printf("Enter data:\n");
for(i=1;i<=n;i++)
{
printf("x[%d]=",i);
scanf("%f", &x[i]);
printf("y[%d]=",i);
scanf("%f", &y[i]);
}
/* Calculating Required Sum */
for(i=1;i<=n;i++)
{
sumX = sumX + x[i];
sumX2 = sumX2 + x[i]*x[i];
sumY = sumY + y[i];
sumXY = sumXY + x[i]*y[i];
}
/* Calculating a and b */
b = (n*sumXY-sumX*sumY)/(n*sumX2-sumX*sumX);
a = (sumY - b*sumX)/n;
/* Displaying value of a and b */
printf("Values are: a=%0.2f and b = %0.2f",a,b);
printf("\nEquation of best fit is: y = %0.2f + %0.2fx",a,b);
getch();
return(0);
}
Practical-4
Fitting a Parabola
Let y = ax2 + bx + c be the parabola to be fitted to the given set of
data points (x1, y1) , (x2, y2),· · · , (xn, yn).
Algorithm to fit a parabola to given set of data points
1. Start
2. Find number of pairs of data points (n) to be fitted
3. Input the x values and y values.
Σ Σ Σ Σ Σ Σ Σ
4. Find x, y, x2, x3, x4, xy and x2y
5.Solve the system of equations given by (1), (2) and (3) using matrix method, where
C = A−1B
6.Requiredparabola to be fitted is y = ax2 + bx + c
7.Stop
4.write a program to fit a parabola=ax2+bx+c
Program:
#include <stdio.h>
#include <math.h>
int main(void)
{
double a,b,c,root1,root2;
printf(" Please enter a \n");
scanf("%lf",&a);
printf(" Please enter b \n");
scanf("%lf",&b);
printf(" Please enter c \n");
scanf("%lf",&c);
root1 = (-b + sqrt(b*b-4.*a*c) ) / (2.*a);
root2 = (-b - sqrt(b*b-4.*a*c) ) / (2.*a);
printf("\n First root is %lf ",root1);
printf("\n Second root is %lf ",root2);
printf("\n ");
return 0;
}
OUTPUT:
Root 1 : 2
Root 2: 3
Root 3:
Practical -5
5. Write a program to fit an exponential curve Y=aebx
Program:
from scipy.optimize import curve_fit
def exponential_curve(x, a, b):
return a * np.exp(b * x)
def fit_exponential_curve(X, Y):
params, covariance = curve_fit(exponential_curve, X, Y)
a, b = params
return a, b
def plot_exponential_fit(X, Y, a, b):
plt.scatter(X, Y, label='Data points')
X_range = np.linspace(min(X), max(X), 100)
Y_fit = exponential_curve(X_range, a, b)
plt.plot(X_range, Y_fit, color='red', label=f'Exponential Fit: Y = {a:.2f}e^({b:.2f}x)')
plt.xlabel('X')
plt.ylabel('Y')
plt.legend()
plt.show()
X = np.array([1, 2, 3, 4, 5])
Y = np.array([2, 7, 20, 54, 148])
a, b = fit_exponential_curve(X, Y)
print(f"Coefficient a: {a:.2f}")
print(f"Coefficient b: {b:.2f}")
plot_exponential_fit(X, Y, a, b)
OUTPUT:
Coefficient a: 1.00
Coefficient b: 1.50
Practical -6
6. Write a program for Runge kutta second order method
Program:
Problem: dy
dx =− y with the initial condition y (x=0)=1 find y(x) for 0 <x<2
#include <stdio.h>
#include <math.h>
int main()
{float k1, k2, x0, l, y0, h, x1, y1;
int n,i;
printf("enter the value of n \n");
scanf("%d",&n);
printf("enter the initial point x0, last point L and initial condition y0:\n");
scanf("%f %f %f",&x0,&l,&y0);
h=(l-x0)/n;
for(i=1;i<=n;i++)
{x1=x0+h;
k1=-h*y0;
k2=-h*(y0+k1);
y1=y0+0.5*(k1+k2);
printf("x[%d] and y[%d]:%f\t\t%f \n",i,i,x1,y1);
x0=x1;
y0=y1;}
return 0;}
Output of the program:
enter the value of n
5
enter the initial point x0, last point L and initial condition y0:
021
x[1] and y[1]:0.400000 0.680000
x[2] and y[2]:0.800000 0.462400
x[3] and y[3]:1.200000 0.314432
x[4] and y[4]:1.600000 0.213814
x[5] and y[5]:2.000000 0.145393
Practical -7
Euler’s Method
Algorithm to solve an initial value problem using Euler’s
method:
1. Start
2. Define and Declare function ydot representing dy
= f (x, y)
dx
3. Input x0, y0 , h and xn for the given initial value condition y(x0) = y0. h is
step size and xn is final value of x.
4. For x = x0 to xn solve the D.E. in steps of h using inbuilt function ode.
5. Print values of x0 to xn and y0 to yn
6. Plot graph in (x, y)
7. Stop
Flow Chart for Euler’s Method
7. write a program to implement the Euler’s Function
Program:
#include<stdio.h>
float fun(float x,float y)
{
float f;
f=x+y;
return f;
}
main()
{
float a,b,x,y,h,t,k;
printf("\nEnter x0,y0,h,xn: ");
scanf("%f%f%f%f",&a,&b,&h,&t);
x=a;
y=b;
printf("\n x\t y\n");
while(x<=t)
{
k=h*fun(x,y);
y=y+k;
x=x+h;
printf("%0.3f\t%0.3f\n",x,y);
}
}
OUTPUT:
Practical -8
Simpson’s 3/8th Rule
Numerical Integration by Simpson’s 3/8th Rule Algorithm:
1. Start
2. Define and Declare function y = f (x) whose integral is to be
computed.
∫b
3. Input a, b and n, where a, b are lower and upper limits of f
integral a
(x)dx
and n is number of intervals in which area is to be divided. Note that n
must be a multiple of 3.
4. Put x1 = a and initialize sum = f (a)
5. Compute x(i) = x(i − 1) + h
6. sum = sum + 3[f (x2) + f (x5) +.......]
7. sum = sum + 3[f (x3) + f (x6) +.......])
8. sum = sum + 2[f (x4) + f (x7) +.......]
9. sum = sum + f (b)
10. val = 3h
(sum)
8
11. Print value of integral.
12. Stop
Flow Chart for Simpson’s 3/8th Rule
8. Write a Program to implement Simpson’s 3/8 rule
Program:
#include<stdio.h>
#include<math.h>
double f(double x){
return x*x;
main(){
int n,i;
double a,b,h,x,sum=0,integral;
printf("\nEnter the no. of sub-intervals(MULTIPLE OF 3): ");
scanf("%d",&n);
printf("\nEnter the initial limit: ");
scanf("%lf",&a);
printf("\nEnter the final limit: ");
scanf("%lf",&b);
h=fabs(b-a)/n;
for(i=1;i<n;i++){
x=a+i*h;
if(i%3==0){
sum=sum+2*f(x);
else{
sum=sum+3*f(x);
integral=(3*h/8)*(f(a)+f(b)+sum);
printf("\nThe integral is: %lf\n",integral);
}
OUTPUT:
Practical -9
Simpson’s 1/3rd Rule
Numerical Integration by Simpson’s 1/3rd Rule Algorithm:
3. Start
4. Define and Declare function y = f (x) whose integral is to be
computed.
∫b
3. Input a, b and n, where a, b are lower and upper limits of f
integral a
(x)dx
and n is number of intervals in which area is to be divided. Note
that n
must be even.
4. Put x1 = a and initialize sum = f (a)
5. Compute x(i) = x(i − 1) + h
6. sum = sum + 4[f (x2) + f (x4) +........+ f (xn))
7. sum = sum + 2[f (x3) + f (x5) +........+ f (xn−1))
8. sum = sum + f (b)
9. val = h(sum)
3
10. Print value of integral.
11. Stop
Flow Chart for Simpson’s 1/3rd Rule
9. Write a Program to implement Simpson’s 1/3rd Rule
Program:
#include<stdio.h>
#include<conio.h>
#include<math.h>
/* Define function here */
#define f(x) 1/(1+x*x)
int main()
{
float lower, upper, integration=0.0, stepSize, k;
int i, subInterval;
clrscr();
/* Input */
printf("Enter lower limit of integration: ");
scanf("%f", &lower);
printf("Enter upper limit of integration: ");
scanf("%f", &upper);
printf("Enter number of sub intervals: ");
scanf("%d", &subInterval);
/* Calculation */
/* Finding step size */
stepSize = (upper - lower)/subInterval;
/* Finding Integration Value */
integration = f(lower) + f(upper);
for(i=1; i<= subInterval-1; i++)
{
k = lower + i*stepSize;
if(i%2==0)
{
integration = integration + 2 * f(k);
}
else
{
integration = integration + 4 * f(k);
}
}
integration = integration * stepSize/3;
printf("\nRequired value of integration is: %.3f",
integration);
getch();
return 0;
}
Output
Enter lower limit of integration: 0
Enter upper limit of integration: 1
Enter number of sub intervals: 6
Required value of integration is: 0.785
Practical -10
The Trapezoidal Rule
Numerical Integration by Trapezoidal Rule Algorithm:
1. Start
2. Define and Declare function y = f (x) whose integral is to be
computed.
3. Input a, b and n, where a, b are lower and upper limits of f
integral (x)dx
and n is number of trapezoids in which area is to be
4. Initialize two counters sum1 and sum2 to zero.
5. Compute x(i) = a + i ∗ h and y(i) = f (x(i)) in a loop for all
n + 1 points dividing n trapezoids.
6. sum1 = y(1) + y(n) and sum2 = y(2) + . . . + y(n − 1)
h/2(sum1+sum2)
7. val =
2
8. Print value of integral.
9. Stop
Flow Chart for Trapezoidal Rule
10:Write a program to implement trapezoidal rule
#include<stdio.h>
#include<conio.h>
#include<math.h>
/* Define function here */
#define f(x) 1/(1+pow(x,2))
int main()
{
float lower, upper, integration=0.0, stepSize, k;
int i, subInterval;
clrscr();
/* Input */
printf("Enter lower limit of integration: ");
scanf("%f", &lower);
printf("Enter upper limit of integration: ");
scanf("%f", &upper);
printf("Enter number of sub intervals: ");
scanf("%d", &subInterval);
/* Calculation */
/* Finding step size */
stepSize = (upper - lower)/subInterval;
/* Finding Integration Value */
integration = f(lower) + f(upper);
for(i=1; i<= subInterval-1; i++)
{
k = lower + i*stepSize;
integration = integration + 2 * f(k);
}
integration = integration * stepSize/2;
printf("\nRequired value of integration is: %.3f", integration);
getch();
return 0;
}
Output:
Enter lower limit of integration: 0
Enter upper limit of integration: 1
Enter number of sub intervals: 6
Required value of integration is: 0.784
Practical -11
Bisection Method
Bisection Method Algorithm:
1. Start
2. Read y = f (x) whose root is to be computed.
3. Input a and b where a, b are end points of interval (a, b) in
which the root lies.
4. Compute f (a) and f (b).
5. If f (a) and f (b) have same signs, then display function
must have different signs at a and b, exit. Otherwise go
to next step.
6. Input e and set iteration number counter to zero. Here e is
the absolute error i.e. the desired degree of accuracy.
7. root = (a + b)/2
8. If f (root) ∗ f (a) > 0, then a = root else b = root
9. Print root and iteration number
10. If |a − b| > 2e, print the root and exit otherwise continue in the
loop
11. Stop
Flow Chart for Bisection Method
11.Write a program to implement bisection program
Program:
#include<stdio.h>
#include<math.h>
double F( double x) //Function definition
{
//This return the value of the Function
return (10 - pow(x,2));
}
int main()
{
printf("Studytonight - Best place to learn\n");
printf("This program illustrates the bisection method in C:\n");
printf(" f(x) = 10 - x^2");
double x0,x1;
printf("\nEnter the first approximation to the root : ");
scanf("%lf",&x0);
printf("Enter the second approximation to the root : ");
scanf("%lf",&x1);
int iter;
printf("Enter the number of iteration you want to perform : ");
scanf("%d",&iter);
int ctr = 1;
double l1 = x0;
double l2 = x1;
double r,f1,f2,f3;
//We check if the initial approximations are the root or not
if(F(l1)==0)// it is a root
r = l1;
else if(F(l2)==0)
r = l2;
else //If the above two values are not the roots of the given function
{
while(ctr <= iter) //Since, ctr is initialized to 1
{
//This is an implementation of the algorithm mentioned above
f1 = F(l1);
r = (l1+l2)/2.0; //Returns a double value
f2 = F(r);
f3 = F(l2);
if(f2 == 0)
{
r = f2;
break; //Execution moves out of the while loop to the
statement just after it
}
printf("The root after %d iteration is %lf\n",ctr,r);
if(f1*f2 < 0)//Both are of opposite sign
l2 = r;
else if(f2*f3 < 0)
l1 = r;
ctr++;
}
}
printf("The approximation to the root is %lf\n",r); //Gives the final
value after mentioned iteration
printf("Coding is Fun !");
return 0;
}
Output:
f(x) = 10 - x^2
Enter the first approximation to the root : -2
Enter the second approximation to the root : 5
Enter the number of iteration you want to perform : 10
The root after 1 iteration is 1.500000
The root after 2 iteration is 3.250000
The root after 3 iteration is 2.375000
The root after 4 iteration is 2.812500
The root after 5 iteration is 3.031250
The root after 6 iteration is 3.140625
The root after 7 iteration is 3.195312
The root after 8 iteration is 3.167969
The root after 9 iteration is 3.154297
The root after 10 iteration is 3.161133
The approximation to the root is 3.161133
Practical -12
12. Write a program to perform Basic Operations on Matrices
Program:
// main function
int main()
{
// matrix
int a[][3] = { {5,6,7}, {8,9,10}, {3,1,2} };
int b[][3] = { {1,2,3}, {4,5,6}, {7,8,9} };
int c[3][3];
// print both matrix
printf("First Matrix:\n");
display(a);
printf("Second Matrix:\n");
display(b);
// variable to take choice
int choice;
// menu-driven
do
{
// menu to choose the operation
printf("\nChoose the matrix operation,\n");
printf("----------------------------\n");
printf("1. Addition\n");
printf("2. Subtraction\n");
printf("3. Multiplication\n");
printf("4. Transpose\n");
printf("5. Exit\n");
printf("----------------------------\n");
printf("Enter your choice: ");
scanf("%d", &choice);
switch (choice) {
case 1:
add(a, b, c);
printf("Sum of matrix: \n");
display(c);
break;
case 2:
subtract(a, b, c);
printf("Subtraction of matrix: \n");
display(c);
break;
case 3:
multiply(a, b, c);
printf("Multiplication of matrix: \n");
display(c);
break;
case 4:
printf("Transpose of the first matrix: \n");
transpose(a, c);
display(c);
printf("Transpose of the second matrix: \n");
transpose(b, c);
display(c);
break;
case 5:
printf("Thank You.\n");
exit(0);
default:
printf("Invalid input.\n");
printf("Please enter the correct input.\n");
}
}while(1);
return 0;
}
Output:
Matrix A:
[[1 2 3]
[4 5 6]
[7 8 9]]
Matrix B:
[[9 8 7]
[6 5 4]
[3 2 1]]
Matrix Addition (A + B):
[[10 10 10]
[10 10 10]
[10 10 10]]
Matrix Subtraction (A - B):
[[-8 -6 -4]
[-2 0 2]
[ 4 6 8]]
Matrix Multiplication (A * B):
[[ 30 24 18]
[ 84 69 54]
[138 114 90]]
Transpose of Matrix A:
[[1 4 7]
[2 5 8]
[3 6 9]]
Transpose of Matrix B:
[[9 6 3]
[8 5 2]
[7 4 1]]