C :: Aufgabe #104

1 Lösung Lösung öffentlich

Lösen eines linearen Gleichungssystems

Fortgeschrittener - C von eulerscheZhl - 13.03.2016 um 08:32 Uhr
Schreibe ein Programm, das lineare Gleichungssysteme lösen kann.

Im Anhang ist eine .html Datei (kann im Browser geöffnet werden).
Bei der Funktion, die berechnet wird, handelt es sich um ein Polynom 5. Grades.
Was gibt das html Dokument für f(1000) aus?
Es ist hilfreich, die berechnete Funktion zu kennen, um die Frage zu beantworten.

Lösungen:

vote_ok
von devnull (8870 Punkte) - 14.03.2016 um 14:20 Uhr

Konsolenausgabe:


Polynom ax⁵ + bx⁴ + cx³ + dx² + ex + f
a = 1.000000 (1)
b = -5.000000 (-5)
c = 3.000000 (3)
d = 1.000000 (1)
e = -2.000000 (-2)
f = 2.000000 (2)
Polynomwert f(1000) = 995003000998002.001526 (long double)
Polynomwert f(1000) = 995003000998002 (long int)

Quellcode ausblenden C-Code
/*********************
*  Gauss-Elimination
**********************/
#include <stdio.h>
#include <math.h>

#define N  5

/* 
 * 	Polynom f(x) = ax⁵ + bx⁴ + cx³ + dx² + ex + f 
 * 
 *  Werte 0..5 einsetzen und Plonom-Koeffizienten berechnen (f=2 trivial).
 *  Koefizienten bilden Matrix A für Gauss-Eliminationsverfahren.
 *  (s. Sedgewick, Algorithms in C)
 * 
 */ 

long double X[N]      = { 0.L, 0.L, 0.L, 0.L, 0.L };
long double A[N][N+1] = { {   1.L,   1.L,   1.L,  1.L, 1.L,  -2.L},
                          {  32.L,  16.L,   8.L,  4.L, 2.L, -24.L},
                          { 243.L,  81.L,  27.L,  9.L, 3.L, -78.L},
                          {1024.L, 256.L,  64.L, 16.L, 4.L, -56.L},  
                          {3125.L, 625.L, 125.L, 25.L, 5.L, 390.L} };
	
void eliminate() {
	int i, j, k, max;
	long double t;
	
	for (i=0; i < N; i++) {
		max = i;
		for (j=i+1; j < N; j++)
			if (fabs(A[j][i]) > fabs(A[max][i])) 
				max = j;
		for (k=i; k <= N; k++) {
			t = A[i][k];
			A[i][k] = A[max][k];
			A[max][k] = t;
		}
		for (j=i+1; j < N; j++)
			for (k=N; k>=i; k--)
				A[j][k] -= A[i][k] * A[j][i] / A[i][i];
	}
}

void substitute() {
	int j, k;
	long double t;
	
	for (j=N-1; j>=0; j--) {
		t=0.0;
		for (k=j+1; k<N; k++)
			t += A[j][k]*X[k];
		X[j] = (A[j][N] - t) / A[j][j];
	}
}

int main(void) {
	long double x, y;
	long int k[5], lx, ly;
	int i;
	
	eliminate();
	substitute();

	/* long -> double -> long int */
	for (i=0; i<N; i++) 
		k[i] = lrintl(X[i]);

	printf("Polynom ax⁵ + bx⁴ + cx³ + dx² + ex + f\n"); 	
	printf("a = %Lf (%ld)\n", X[0], k[0]);
	printf("b = %Lf (%ld)\n", X[1], k[1]);
	printf("c = %Lf (%ld)\n", X[2], k[2]);
	printf("d = %Lf (%ld)\n", X[3], k[3]);
	printf("e = %Lf (%ld)\n", X[4], k[4]);
	printf("f = %Lf (%ld)\n", 2.0L, 2L);

	/* Funktionswert fuer x=1000 mit Horner-Schema berechnen */
	x  = 1000.L;
	lx = 1000L;
	y  = ((((X[0]*x+X[1])*x+X[2])*x+X[3])*x+X[4])*x+2.0L;
	ly = ((((k[0]*lx+k[1])*lx+k[2])*lx+k[3])*lx+k[4])*lx+2L;
	printf("Polynomwert f(%ld) = %Lf (long double)\n", lx, y);
	printf("Polynomwert f(%ld) = %ld (long int)\n", lx, ly);
	
	return 0;	
}