How can I change the code below to accept all equations?

Dear Friends,
The code below is to calculate the dy/dx = y - x differential equation by second order runge-kutta methods. How can I change it to get an equation from me (I mean other equation) and calculate it by second order runge-kutta method?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
  #include<iostream>  //Header file for cin & cout
 #include<cmath>  //Header file for mathematical operartions
 #include<iomanip> //Header file for precession
 using namespace std;  //calling the standard directory

//Given dy/dx
 float f(float(x),float(y))
 {
 return (y-x);
 }

 int main()
 {
 int n,i,j;
 float h;
 cout<<"Aim : To solve a differential equation by Second Order Runge-Kutta's Method"<<endl;
 cout<<"Given Equtaion is dy/dx = y - x "<<endl;

//Entering the Number of Iterations
 cout<<"Enter the number of solutions "<<endl;
 cin>>n;

//Entering the width of step size
 cout<<"Enter The Value of Step Size "<<endl;
 cin>>h;

 long double y[n],e[n],x[n],Y[n],L[n],k[n][n];

//Entering the initial values of x & y
 cout<<"Enter the value of x0 "<<endl;
 cin>>x[0];
 cout<<"Enter The Value of y0 "<<endl;
 cin>>y[0];

//Calculating the value of x
 for(i=1;i<=n;i++)
 {
 x[i]=x[i-1]+h;
 }

 cout<<"Solution of the given differential equation by Second Order Runga Kutta Method is "<<endl;

//Calculating & Printing the values of k1, k2 & y
 for(j=1;j<=n;j++)
 {
 k[1][j]=h*f(x[j-1],y[j-1]);
 cout<<"K[1] = "<<k[1][j]<<"\t";
 k[2][j]=h*f(x[j-1]+h,y[j-1]+k[1][j]);
 cout<<"K[2] = "<<k[2][j]<<"\n";
 y[j]=y[j-1]+((k[1][j]+k[2][j])/2);
 cout<<"y["<<h*j<<"] = "<<setprecision(5)<<y[j]<<endl;
 }

 return 0;
 }

Last edited on
Topic archived. No new replies allowed.