Skip to content

Instantly share code, notes, and snippets.

@zacharyneveu
Last active March 19, 2017 21:42
Show Gist options
  • Save zacharyneveu/3f90005871f0c51ec2c8110bdd1c6b6f to your computer and use it in GitHub Desktop.
Save zacharyneveu/3f90005871f0c51ec2c8110bdd1c6b6f to your computer and use it in GitHub Desktop.
Calculates cosine using series expansion
//This program gets an angle in radians and calculates its cosine using series expansion.
#include<iostream>
#include<cmath>
using namespace std;
//declare variables and functions here
double angle;
double cosx=1;
//cosine function uses first five terms of series expansion to return the approximate cosine of an angle.
//fact function computes factorial as seen in class.
int fact(int input){
if (input <= 1){
return 1;}
else {
return input*fact(input-1);
}
}
double cosine(double angle){
//For loop iterates over 2, 4, 6, 8, 10.
for(int i=2; i<=10; i+=2){
//Term variable stores number from one term of sequence
double term = pow(angle, i)/fact(i);
//every other term is either added or subtracted.
if(i%4==0){
cosx = cosx + term;}
else{
cosx = cosx - term;}
}
return cosx;
}
int main(){
//While loop lets program run indefinitely
while(1==1){
cout<<"please type an angle in radians"<<endl;
cin>>angle;
//calls series expansion cosine and prints it.
cout<<"the series expansion cosine of that is: "<<cosine(angle)<<endl;
//Calls cmath cosine and prints that as well.
cout<<"the c++ cosine of that angle is: "<<cos(angle)<<endl;
//In windows command prompt, CTRL-C stops a program.
cout<<"use <CTRL-C> to quit this program"<<endl;
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment