这里用Python逼近函数y = exp(x);同样使用泰勒函数去逼近:
exp(x) = 1 + x + (x)^2/(2!) + .. + (x)^n/(n!) + ...
#!/usr/bin/python
# -*- coding:utf-8 -*-
import numpy as np
import math
import matplotlib as mpl
import matplotlib.pyplot as plt
def calc_e_small(x):
n = 10
f = np.arange(1, n+1).cumprod()
b = np.array([x]*n).cumprod()
return np.sum(b / f) + 1
def calc_e(x):
reverse = False
if x < 0: # 处理负数
x = -x
reverse = True
ln2 = 0.69314718055994530941723212145818
c = x / ln2
a = int(c+0.5)
b = x - a*ln2
y = (2 ** a) * calc_e_small(b)
if reverse:
return 1/y
return y
if __name__ == "__main__":
t1 = np.linspace(-2, 0, 10, endpoint=