Skip to content

Commit

Permalink
Add a C version
Browse files Browse the repository at this point in the history
  • Loading branch information
certik committed Jan 2, 2012
1 parent 805f606 commit 856b6da
Show file tree
Hide file tree
Showing 4 changed files with 76 additions and 0 deletions.
30 changes: 30 additions & 0 deletions c/a.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
#include <stdio.h>
#include <stdlib.h>

#include "compute.h"

void derivs(double x, double y, double *dx, double *dy, void *data)
{
char *str = data;
if (str == "eq1") {
*dx = -y;
*dy = x;
} else if (str == "eq2") {
*dx = y;
*dy = x;
} else {
printf("Not implemented...\n");
abort();
}
}

int main()
{
eq d;
init(d);
register_func(d, derivs);
run(d, 0, 1, 0.1, 10, "eq1");
printf("\n");
run(d, 0, 1, 0.1, 10, "eq2");
return 0;
}
6 changes: 6 additions & 0 deletions c/compile
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
#! /bin/bash

set -e
gcc -c a.c -o a.o
gcc -c compute.c -o compute.o
gcc -o a a.o compute.o
29 changes: 29 additions & 0 deletions c/compute.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
#include <stdio.h>

#include "compute.h"

void init(eq d)
{
}

void register_func(eq d, derivs_pt func)
{
d.func = func;
}

void run(eq d, double x0, double y0, double dt, double n_steps,
void *data)
{
double x, y, dx, dy, t;
int i;
x = x0;
y = y0;
t = 0;
for (i=0; i < n_steps; i++) {
d.func(x, y, &dx, &dy, data);
printf("%f %f\n", x, y);
x += dx * dt;
y += dy * dt;
t += dt;
}
}
11 changes: 11 additions & 0 deletions c/compute.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
typedef void (*derivs_pt)(double x, double y, double *dx, double *dy,
void *data);

typedef struct {
derivs_pt func;
} eq;

void init(eq d);
void register_func(eq d, derivs_pt func);
void run(eq d, double x0, double y0, double dt, double n_steps,
void *data);

0 comments on commit 856b6da

Please sign in to comment.