Programmiersprachen (Re: [linux-l] Ruby: sehr cool, aber laaaahm... wie geht's schneller?! - D?)

Axel Weiß aweiss at informatik.hu-berlin.de
Do Aug 24 21:40:44 CEST 2006


Oliver Bandel wrote:
> Vorschläge in anderen Sprachen?
> (Perl, Java, C, ...?!)

Hier, 15 Minuten:
--------------------------------
#include <stdio.h>
#include <math.h>

#define BERECHNUNGEN 64
#define SCHRITT 0.1
static const double eps = 0.001;

static double sq(double);
static double qb(double);

typedef double (*f_t)(double);
static double derive(f_t, double);

static const struct {
	f_t f;
	const char *name;
} function_table[] = {
	{sin, "Sinus"},
	{cos, "Kosinus"},
	{sq,  "Quadrat (Parabel)"},
	{qb,  "Kubik"},
	/* hier weitere Funktionen reinstecken */
};

int main(){
	int i, j;
	for (i=0; i<sizeof(function_table)/sizeof(function_table[0]); ++i){
		printf("\n\nBerechnung von %s:\n", function_table[i].name);
		for (j=0; j<BERECHNUNGEN; ++j){
			double x = SCHRITT * j;
			double y = function_table[i].f(x);
			double dy = derive(function_table[i].f, x);
			printf("x: %f, y: %f, y': %f\n", x, y, dy);
		}
	}
}

static double sq(double x){
	return x * x;
}

static double qb(double x){
	return x * x * x;
}

static double derive(f_t f, double x){
	double d = f(x + eps / 2) - f(x - eps / 2);
	return d / eps;
}
--------------------------------

Nette Übung ;)

Gruß,
			Axel





Mehr Informationen über die Mailingliste linux-l