All pastes #332565 Raw Edit

brent

public cpp v1 · immutable
#332565 ·published 2007-01-30 02:33 UTC
rendered paste body
/* sin-approx, an approximation example. * Copyright (C) 2007 Brent Barker, b.w.barker@smokejive.net, P.O. Box 1246, * Indiana, PA 15701 USA * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU Public License as published by the Free Software * Foundation; either version 2 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program; if not, write to the Free Software Foundation, Inc., 51 * Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA */ /* Program calculates the sine of 3 hard-coded angles using an ever * increasing number of terms from the Taylor Series and displays the * sine as calculated using the sin function from the cmath library. * * Last Modified: 24 Jan 2007 */#include <iostream>#include <cmath>#include <iomanip>using namespace std;int main(){	double PI = 4.*atan(1.); // gives machine-precision value for pi		/* Three values to be used in the calculations */	double x = PI / 4.;	double y = 3. * PI / 4.;	double z = 17. * PI / 4.;		/* squares are used in innermost loop. This saves N-1 operations */	double x2 = x*x;	double y2 = y*y;	double z2 = z*z;		double totalx, totaly, totalz, div;	double neg; // determines whether new term is negative or positive	int totTerms = 32; // how many terms to go out to in the Taylor series		cout << "No. Terms\t" << "Sine of pi / 4\t\t" << "Sine 3 pi / 4\t\t"			<< "Sine 17 pi / 4" << endl;		/* Loop through how many terms to use */	for (int terms = 0; terms < totTerms; terms++)	{		cout << terms+1 << "\t\t";				/* Initialize totals */		totalx = 0;		totaly = 0;		totalz = 0;				/* Loop through modified Horner polynomial method */		for (int cterms = terms; cterms >=0; cterms--)		{			if (cterms%2==0)				neg = 1.;			else				neg = -1.;						div = (cterms * 2. + 1.) * (cterms*2.);			if (cterms==0)				div=1.;						totalx = (totalx*x2+x*neg)/div;			totaly = (totaly*y2+y*neg)/div;			totalz = (totalz*z2+z*neg)/div;		}				cout << showpoint << setprecision(16) << totalx << "\t" <<totaly << "\t" << totalz << endl;	}		cout << "sin()\t\t" << sin(PI / 4.) << "\t" << sin(3*PI/4.) << "\t" <<sin(17*PI/4.) << endl;	return 0;}