指数函数的近似
2019-04-08 本文已影响0人
Jianbaozi
捕获.JPG
#include "Graph.h"
#include "Simple_window.h"
using namespace Graph_lib;
double fac(int n);
double term(double x, int n);
double expe(double x, int n);
int expN_number_of_terms = 10;
double expN(double x)
{
return expe(x, expN_number_of_terms);
}
int main()
{
constexpr int xmax = 600;
constexpr int ymax = 400;
constexpr int x_orig = xmax / 2;
constexpr int y_orig = ymax / 2;
Point orig{ x_orig,y_orig };
constexpr double r_min = -10;
constexpr double r_max = 11;
constexpr int n_points = 400;
constexpr int x_scale = 30;
constexpr int y_scale = 30;
constexpr int xlength = xmax - 40;
constexpr int ylength = ymax - 40;
Simple_window win{ Point{100,100},xmax,ymax,"Wanbabe" };
Axis x{ Axis::x,Point{20,y_orig},xlength,xlength / x_scale,"one notch==1" };
Axis y{ Axis::y,Point{x_orig,ylength+20},ylength,ylength / y_scale,"one notch==1" };
x.set_color(Color::red);
x.label.set_color(Color::blue);
y.set_color(Color::red);
Function real_exp{ exp,r_min,r_max,orig,200,double(x_scale),double(y_scale) };
real_exp.set_color(Color::blue);
win.attach(real_exp);
win.attach(x);
win.attach(y);
for (int n = 0; n < 20; ++n) {
ostringstream ss;
ss<< "exp approximation;n=" << n;
win.set_label(ss.str());
expN_number_of_terms = n;
Function e(expN, r_min, r_max, orig, 200, x_scale, y_scale);
win.attach(e);
win.wait_for_button();
win.detach(e);
}
}
double fac(int n) {
int r = 1;
while (n > 1) {
r *= n;
--n;
}
return r;
}
double term(double x, int n) {
return pow(x, n) / fac(n);
}
double expe(double x, int n) {
double sum = 0;
for (int i = 0; i < n; ++i)
sum += term(x, i);
return sum;
}