Εύρεση της τιμής του sin(x) με τη χρήση αθροίσματος σειρών

Πρόγραμμα εύρεσης της τιμής του sin(x) χρησιμοποιώντας άθροισμα σειρών μέχρι μια επιθυμητή ακρίβεια (accuracy). Για τη σύγκριση των αποτελεσμάτων γίνεται χρήση και της έτοιμης συνάρτησης sin(x) της βιβλιοθήκης "math.h" .

#include <stdio.h>
#include <stdlib.h>
#include <math.h>

void mysin(float x, float accuracy);

void main()
{
	int option = 1;
	float x, accuracy;

	while (option)
	{
		printf("\n sin(x) calculation using series.\n");
		printf("\n --------------------------------\n");
		printf("\n\n Enter the value of x (in degrees): ");
		scanf("%f", &x);

		printf("\n Enter the accuracy for the result: ");/*example: 0.001*/
		scanf("%f", &accuracy);

		/* Call function mysin() */
		mysin(x, accuracy);

		fflush(stdin);
		printf("\n______________________________________________________\n");
		printf("\n Do you want to calculate new sin(x)? [Type 0 or 1]: ");
		scanf("%d", &option);
		system("cls");
	}
}

void mysin(float x, float accuracy)
{
	int n, x1;
	float  term, den, sinx = 0, sinvalue;

	if (accuracy > 0 && x <= 360 && x >= -360)
	{
		/* Keep value of x in x1 */
		x1 = x;

		/* Convert degrees to radians*/
		x = x*(3.142 / 180.0);
		sinvalue = sin(x);

		term = x;
		sinx = term;
		n = 1;

		/* Value of accuracy is used as condition for the while loop */
		do
		{
			den = 2 * n*(2 * n + 1);
			term = -term * x * x / den;
			sinx = sinx + term;
			n = n + 1;

		} while (accuracy <= fabs(sinvalue - sinx));

		/* Results printing */
		printf("\n -- RESULT -- \n");
		printf("\n Sum of the sine series= %f", sinx);

		/* Not necessary for our sinx fuction
		Just using it for comparison reasons ... */
		printf("\n Using math.h Library function sin(%d)= %f", x1, sin(x));
		printf("\n\n");
	}
	else
	{
		printf("\n\n Input Error !");
		printf("\n Acurracy must be a value greater than zero.\n");
		printf(" Degrees must be between -360 and 360.\n");
	}
}
ċ
sinx-exe..zip
(97k)
Dimitrios Rousis,
8 Μαρ 2014, 5:17 μ.μ.
ċ
sinx.c
(2k)
Dimitrios Rousis,
8 Μαρ 2014, 1:48 μ.μ.