Uploaded by vofim67417

19BME0766-CSE1002-DA1

advertisement
DA-1
MUGILAN.M
19BME0766
Write C and C++ programs to solve a first-order ordinary differential equation (ODE) for an
initial value problem (IVP). Explain the logic and algorithm with a suitable problem
statement using the Euler method.
EULER METHOD
Initial value problems (IVPs) are numerical problems that are solved by solving first-order
ordinary differential equations (ODEs) using the Euler method. By taking a series of small
steps, the method approximates the ODE's exact solution. The method determines the next
point on the solution curve at each step by computing the derivative of the ODE at the
current point and using that derivative. The approach is based on the idea of approximating
the behavior of the solution over a brief period by making small steps in the direction of the
derivative. The Euler method is a quick and efficient way to solve first-order ODEs, but it is
only accurate for small time steps, and if the step size is too large, it can result in large
errors.
ALGORITHM AND LOGIC
● Let us assume that dy/dx=x+y and y(0)=1 are the initial conditions.
● Set the initial values for the step size "h," which is the distance between x-values and
x0 and y0.
● To iterate over the desired range, create a loop that increases x by h each time.
● Utilize the ODE inside the loop to determine the slope of the tangent line at the
current point: slope=f(x,y)=x+y.
● Update the value of y by moving a little bit in the tangent line's direction:
y=y+slope*h.
● As the rough solution, print the current values of x and y.
● In order to cover the desired range, repeat steps 3 through 5.
C PROGRAM
#include <stdio.h>
double f(double x, double y) {
return x + y;
}
void eulerMethod(double x0, double y0, double h, double range) {
double x = x0;
double y = y0;
printf("Approximate solution:\n");
printf("x = %.2f, y = %.6f\n", x, y);
while (x < range) {
double slope = f(x, y);
y = y + slope * h;
x = x + h;
printf("x = %.2f, y = %.6f\n", x, y);
}
}
int main() {
double x0 = 0.0; // Initial x-value
double y0 = 1.0; // Initial y-value
double h = 0.1; // Step size
double range = 1.0; // Range of x-values
eulerMethod(x0, y0, h, range);
return 0;
}
C++ PROGRAM
#include <iostream>
double f(double x, double y) {
return x + y;
}
void eulerMethod(double x0, double y0, double h, double range) {
double x = x0;
double y = y0;
std::cout << "Approximate solution:" << std::endl;
std::cout << "x = " << x << ", y = " << y << std::endl;
while (x < range) {
double slope = f(x, y);
y = y + slope * h;
x = x + h;
std::cout << "x = " << x << ", y = " << y << std::endl;
}
}
int main() {
double x0 = 0.0; // Initial x-value
double y0 = 1.0; // Initial y-value
double h = 0.1; // Step size
double range = 1.0; // Range of x-values
eulerMethod(x0, y0, h, range);
return 0;
}
Download