# Runge Kutta Projectile Problem

This is a discussion on Runge Kutta Projectile Problem within the C Programming forums, part of the General Programming Boards category; Hi, I'm onto a second part of a problem sheet I've been given, and I've had to modify some code(that ...

1. ## Runge Kutta Projectile Problem

Hi, I'm onto a second part of a problem sheet I've been given, and I've had to modify some code(that previously worked fine) to use the Runge Kutta method for solving ODE's. I have my code, shown below, but its outputting a straight line, and I dont know why. It should be a projectile parabola. I've been looking at this for hours now and can't figure out what's wrong. Any help is appreciated.

Code:
```#include <stdio.h>#include <stdlib.h>
#include <math.h>

const double pi = 3.141592654, g = 9.81; //define constants for easy use

#define F(x,y) ((Uy/Ux)-(g*x)/(pow(Ux, 2))) //defining projectile function
int main()

{
FILE *myfile;
double U, theta, Ux, Uy, h, x, y1, y2, k1, k2, k3, k4;

printf("Enter a launch speed between 0 and 22 in m/s\n");//0 and 22 explained in report
scanf("%lf", &U);

printf("Enter, in degrees, the angle of elevation you wish to shoot at\n");
scanf("%lf", &theta);

Ux = U*cos(theta*pi/180);// x component of velocity
Uy = U*sin(theta*pi/180);//y component of velocity

x=0;
h=0.1;
k1 =h*F(x,y1);
k2 =h*F(x+(h/2), y1+(k1/2));
k3=h*F(x+(h/2), y1+(k2/2));
k4=h*F(x+h, y1+k3);

myfile=fopen("myoutput.txt", "w");//open file for results to be sent

do
{
y2 = y1 + k1/6 + k2/3 + k3/3 + k4/6;
x=x+h;
printf("\n\n x= %lf y= %lf", x, y2);//print results in compiler
fprintf(myfile, "\n\n %lf %lf", x,y2);//print results in file
y1=y2;//repeat
}
while (y2>0);

fclose(myfile);

return 0;
}```

2. > #define F(x,y) ((Uy/Ux)-(g*x)/(pow(Ux, 2))) //defining projectile function
Why doesn't this use y?

Also, you need to be REALLY CAREFUL with macro functions.

> k2 =h*F(x+(h/2), y1+(k1/2));
Expands as
> ((Uy/Ux)-(g*x+(h/2))/(pow(Ux, 2)))

That is, you're only doing g*x, whereas it would seem you intended g*(x+(h/2))

Write it as a proper function to begin with.
There's no excuse for a function-like macro here.

3. That function was just one given to me, its a result of the chain rule to eliminate time from the projectile equations.

I've modified my code so now the k's are
Code:
```k1 = h*(Uy/Ux)-(g*x)/(pow(Ux, 2));	k2 = h*(Uy/Ux)-(g*(x+h/2))/(pow(Ux, 2));
k3 = h*(Uy/Ux)-(g*(x+h/2))/(pow(Ux, 2));
k4 = h*(Uy/Ux)-(g*(x+h))/(pow(Ux, 2));```
But im still getting a straight line, and so my y<0 condition isn't stopping the loop...