c++ - Trying to compute e^x when x_0 = 1 -


i trying compute taylor series expansion e^x @ x_0 = 1. having hard time understanding looking for. pretty sure trying find decimal approximation when e^x when x_0 = 1 is. however, when run code when x_0 = 0, wrong output. leads me believe computing incorrectly.

here class e.hpp

#ifndef e_hpp #define e_hpp  class e {     public:         int factorial(int n);         double computee();      private:         int fact = 1;         int x_0 = 1;         int x = 1;         int n = 10;         double e = 2.718;         double sum = 0.0;  }; 

here e.cpp

#include "e.hpp" #include <cmath> #include <iostream>  int e::factorial(int n) {     if(n == 0) return 1;     for(int = 1; <= n; ++i)     {         fact = fact * i;     }      return fact; }  double e::computee() {     sum = std::pow(e,x_0);      for(int = 1; < n; ++i)     {         sum += ((std::pow(x-x_0,i))/factorial(i));     }     return e * sum; } 

in main.cpp

#include "e.hpp" #include <iostream> #include <cmath>  int main() {     e a;     std::cout << "e calculated @ x_0 = 1: " << a.computee() << std::endl;     std::cout << "e calculated std::exp: " << std::exp(1) << std::endl; } 

output:
e calculated @ x_0 = 1: 7.38752
e calculated std::exp: 2.71828

when change x_0 = 0.
e calculated @ x_0 = 0: 7.03102
e calculated std::exp: 2.71828

what doing wrong? implementing taylor series incorrectly? logic incorrect somewhere?

yeah, logic incorrect somewhere.

like dan says, have reset fact 1 each time calculate factorial. might make local factorial function.

in return statement of computee multiplying sum e, not need do. sum taylor approximation of e^x.

the taylor series e^x 0 sum _i=0 ^i=infinity (x^i / i!), x_0 should indeed 0 in program.

technically computee computes right value sum when have x_0=0, it's kind of strange. taylor series starts @ i=0, start loop i=1. however, first term of taylor series x^0 / 0! = 1 , initialize sum std::pow(e, x_0) = std::pow(e, 0) = 1 works out mathematically.

(your computee function also computed right value sum when had x_0 = 1. initialized sum std::pow(e, 1) = e, , loop didn't change value @ because x - x_0 = 0.)

however, said, in either case don't need multiply e in return statement.

i change computee code this:

double e::computee() {     sum = 0;     for(int = 0; < n; ++i)     {         sum += ((std::pow(x-x_0,i))/factorial(i));         cout << sum << endl;     }     return sum; } 

and set x_0 = 0.


Comments

Popular posts from this blog

resizing Telegram inline keyboard -

command line - How can a Python program background itself? -

php - "cURL error 28: Resolving timed out" on Wordpress on Azure App Service on Linux -