Skip to content

Instantly share code, notes, and snippets.

@Corwinpro
Last active December 27, 2015 11:49
Show Gist options
  • Select an option

  • Save Corwinpro/7321413 to your computer and use it in GitHub Desktop.

Select an option

Save Corwinpro/7321413 to your computer and use it in GitHub Desktop.
Euler + Runge
#define _CRT_SECURE_NO_DEPRECATE
#include "stdio.h"
#include "math.h"
#include "conio.h"
#include <iostream>
double step = 0.1;
double function(double t, double x)
{
if (t == 0)
return 1.0;
if (t < 0)
return -1;
return -x;
}
double get_x(double prev_t, double prev_x)
{
if (prev_t == 0)
return 1.0;
return prev_x + step * function(prev_t,prev_x);
}
void euler()
{
double t = 0.0
double x = 0.0;
FILE * file;
file = fopen("file.txt", "w");
while (t < 3.0)
{
fprintf(file, "%.8e %.8e\n", t, x = get_x(t, x));
t = t + step;
}
fclose(file);
}
void runge()
{
double t = 0.0
double x = 0.0;
double z;
x = function(t,x);
FILE * file;
file = fopen("file2.txt", "w");
fprintf(file, "%.8e %.8e\n", t, x);
while (t < 3)
{
z = x + step * function(t , x);
x = x + step / 2 * (function(t , x) + function(t += step, z));
fprintf(file, "%.8e %.8e\n", t, x);
}
fclose(file);
}
void main()
{
euler();
runge();
getchar();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment