I'm having trouble with a for loop!
I'm trying to solve a differential equation using Euler's method like so;
\displaystyle\frac{dy}{dx} = 7{y^2}cos(y^2)-3e^{xy}, \ \ \ 0 \leq x \leq 1 \ \ \ y(0) = 0
This is solved using the algorithm
y_{n+1} = y_n + hf(x_n , y_n)
Where h is the step size and f is the right hand side of the ODE.
Now, I need to write a program to solve this ODE , using an appropriate step size, and outputting a table of values with x and y in the range 0\leq x \leq 1
Heres my program;
#include <stdlib.h>
#include <iostream>
#include <cmath>
#include <fstream>
using namespace std;
double f(double x, double y)
{
return 7*y*y*cos(y*y)-3*exp(x*y);
}
int main()
{
ofstream output;
// Define an output file to store the table
output.open("/home/mbbx7ms5/NetBeansProjects/Data/coursework3data.csv");
if(!output.is_open())
{
cout << " File not opened \n";
throw;
}
double n=100.;
double h=1./n;
double y_new,y_curr;
y_curr=0;
for(int i=1;i<=n;i++)
{
float x_i=h*i;
y_new = y_curr + h*f(x_i,y_curr);
y_curr = y_new;
output << i << " , " << x_i << " , " << y_curr << "\n";
}
}
Here, I've just set n=100 so the step size is h=0.01.
Now what I want to do is run the program with different values of n, say, ranging from 10 to 10000.
How do I change my code so that I get a table of increasing values for n, with corresponding values for y(1).
I initially tried putting in another for loop for values of n, increasing in increments of 100. But the problem I got was that the table displayed all values of y_i, when I just want the last value.
Can someone help me? I ultimately want to show that the solution converges for larger values of n.
Thanks in advance!