C :: Aufgabe #134

1 Lösung Lösung öffentlich

Cosinus Näherungsverfahren

Anfänger - C von vk_26 - 09.11.2016 um 12:49 Uhr
- Main Methode, die eine Benutzereingabe (eine
Dezimalzahl) liest.

- Das Programm soll den Cosinus dieser Zahl berechnen. Dazu sollen Sie ein
Näherungsverfahren verwenden und dieses mit der Bibliotheksfunktion Math.cos() vergleichen.
Eine Näherung lautet: cos(x) = 1 - ( x ^ 2 / 2 ! ) + ( x ^ 4 / 4 ! ) - ( x ^ 6 / 6 ! ) + ....

Sie sollen diese Reihe fortsetzen, solange der zu addierende Term betragsmäßig größer als 10-6 ist. Dann geben Sie das Ergebnis, das
Resultat der Bibliotheksfunktion, und die Anzahl von Termen, die sie addieren mussten, aus.

Stellen Sie sicher, dass auch negative Eingaben und 0 korrekt behandelt werden. Beispiel:

Eingabe: 1,5

Ausgabe: 0.07073693411690848 Bibliothek: 0.0707372016677029 Terme: 5

- Was passiert bei der Eingabe von 30, 40 oder 50? Haben Sie eine Idee, wie das Problem lösbar
wäre?

Lösungen:

vote_ok
von devnull (8870 Punkte) - 14.11.2016 um 16:31 Uhr

Konsolenausgabe:

Eingabe    : 50
norm. Wert : 6.0177028497
Näherung : 0.9649664641
Bibliothek : 0.9649660285
Anz. Terme : 12

Quellcode ausblenden C-Code
/********************************************
 * cosinus.c  cos - Näherung
 ********************************************/
#include <stdlib.h>
#include <stdio.h>
#include <math.h>

int counter;

/* Berechnungsfunktionen */

double bfak(int n) {
	double prod=1.0L;
	int k;

	for (k=2; k<=n; k++)
		prod *= (double)k;

	return prod;
}

double bpow(double base, int e) {
	double pow = 1.0L;
	int k;

	for (k=1; k<=e; k++)
		pow *= base;

	return pow;
}

double taylor(double x) {
	const double eps = 1.0e-6L;
	double add, sum = 1.0L;
	int k;

	counter=k=0;
	while (1) {
		k += 2;
		add = bpow(x,k) / bfak(k);
		if (add < eps)
			break;
		if (k%4)
			sum -= add;
		else
			sum += add;
		counter++;
	};
	return sum;
}

double normalize(double x) {
	const double pi2 = M_PI*2.;

	if (x < 0.) x = -x;
	while (x > pi2)
		x -= pi2;
	return x;
}

/* main */
int main() {
	double x, xn;
	double cos_t, cos_m;

	printf("Eingabe    : ");
	scanf("%lf", &x);
	xn = normalize(x);
	cos_t = taylor(xn);
	cos_m = cos(x);

	printf("norm. Wert : %.10lf\n", xn);
	printf("Näherung   : %.10lf\n", cos_t);
	printf("Bibliothek : %.10lf\n", cos_m);
	printf("Anz. Terme : %d\n", counter);

	return 0;
}