In: Electrical Engineering
1) Write a program in C++
sin(x) can be approximately calculated using the following formula, where n! is factorial(n) – for example 3!=3*2*1 = 6 (the function in previous problem).
The more terms we use in the series, the higher will be accuracy of the calculations. By using infinite terms in the series we will have the exact value.
Hint 1: For n! simply use (copy and paste) the factorialFunc(n)from previous problem.
Hint 2: This problems is similar to the “pi series” problem in the homework problems. A simple for loop is needed. Much easier that it looks.
Write a program that gets x and calculates sin(x) using 10, 100, 1000 and 10,000 terms.
Then run the program and calculate and display the result for x=pi/6.
From the given problem statement, we can conclude that sin(x) is being computed using taylors series.
The C++ code is given below:
#include <iostream>
using namespace std;
double factorial(int x) //calculates the factorial
{
double fact = 1;
for(; x >= 1 ; x--)
{
fact = x * fact;
}
return fact;
}
double power(double x,double n) //calculates the power of
x
{
double output = 1;
while(n>0)
{
output =(
x*output);
n--;
}
return output;
}
float sin(double angle,int numberofterms) //value of sine by
Taylors series
{
double a,b,c;
double result = 0;
for(int y=0 ; y!=numberofterms ; y++)
{
a= power(-1,y);
//sign of the term
b= power(angle,(2*y)+1);
//numerator
c= factorial((2*y)+1);
//denominator
result = result+
(a*b)/c; //1 - x^3/3! + x^5/5! -
x^7/7!+...
}
return result;
}
double angle,output1,output2,output3,output4;
int main()
{
cout<<"enter the value of angle in
radians\t";
cin>>angle;
output1 = sin(angle,9);
output2 = sin(angle,99);
output3 = sin(angle,999);
output4 = sin(angle,9999);
cout<< "\nsine of the given angle for
10 iterations is\t"<< output1;
cout<< "\nsine of the given angle for 100
iterations is\t"<< output2;
cout<< "\nsine of the given angle for 1000
iterations is\t"<< output3;
cout<< "\nsine of the given angle for
10000 iterations is\t"<< output4;
cout<< "\n";
return 0;
}
The snap shot of the code is provided below:
The output for x=pi/6 is shown below. Please note that the result converges for 10 iterations, so we get the same value for other other iterations too.