In: Computer Science
USING C++
1) Write a program that repeatedly evaluates a n-th order polynomial p(x) = a0 + a1*x + a2*x^2 + ... + an*x^n where n <= 10 The program inputs n, ai, and x from the keyboard and then prints out the corresponding value of p to the screen. The program continues to input new values of n, ai, x and evaluates p until a negative value for n is input, at which point the program stops.
2)Write a program that calculates exp(x) using the Taylor series approximation exp_approx = 1 + x + x^2 / 2! + x^3 / 3! + ... where x and error are input from the keyboard and a sufficient number of series terms are used such that abs( exp_approx - exp(x) ) < error. Hint: Use *= in a loop to calculate x^i and i! and print them out to the screen to verify that your loop is correct before calculating the series approximation.
1. C++ code:
#include<iostream>
#include<cmath>
using namespace std;
int main(){
while(true){
int n;
float x;
cout<<"Enter the value of n and x\n";
cin>>n;
if(n<0){
cout<<"End of the program\n";
break;
}
cin>>x;
float ans=0;
for(int i=0;i<=n;i++){
float a;
cout<<"Enter the value of a"<<i<<"\n";
cin>>a;
//ans = ans + ai * x^i
ans = ans + a*pow(x,i);
}
cout<<"value of p is "<<ans<<"\n";
}
return 0;
}
Output:
2. C++ code:
#include<iostream>
#include<cmath>
using namespace std;
int main(){
float x, error;
cout<<"Please enter x and error\n";
cin>>x>>error;
//True value of exp(x)
float exp_value = exp(x);
//Current x^val
float cur_x = x;
//Current val!
float cur_fact = 1;
int val = 2;
//Store exp(x) value calculated through taylor series
float exp_taylor = 1;
while(abs(exp_taylor - exp_value) >= error){
cout<<"x^"<<val-1<<" = "<<cur_x<<" ;
";
cout<<val-1<<"!"<<" = "<<cur_fact<<"
; ";
cout<<"x^"<<val-1<<"/"<<val-1<<"!"<<"
= "<<cur_x/cur_fact<<"\n";
exp_taylor += cur_x/cur_fact;
cur_x *= x;
cur_fact *= val;
val++;
}
cout<<"Approximated value of exp(x) =
"<<exp_taylor<<"\n";
return 0;
}
Output: