1、log函数的简单绘制
1、介绍
使用python语法做出log函数的图像进行显示,代码如下:
# @Time : 2020/12/4 16:16
# @Description : 对于指数函数log的测试
import math
import matplotlib.pyplot as plt
if __name__ == "__main__":
# x坐标范围为[1,299]/100
x = [float(i) / 100.0 for i in range(1, 300)]
y = [math.log(i) for i in x]
plt.plot(x, y, 'r-', linewidth=3, label='log Curve')
# 在图形上标记一条线和两个点
a = [x[20], x[175]]
b = [y[20], y[175]]
plt.plot(a, b, 'g-', linewidth=2)
plt.plot(a, b, 'b*', markersize=15, alpha=0.75)
plt.legend(loc='upper left')
plt.grid(True)
plt.xlabel('x')
plt.ylabel('log(x)')
plt.show()
2、结果展示
2、log函数上升速度比较
1、代码
import math
import matplotlib.pyplot as plt
import numpy as np
if __name__ == "__main__":
x = np.arange(0.05, 3, 0.05)
y1 = [math.log(a, 1.5) for a in x]
plt.plot(x, y1, linewidth=2, color="#007500", label='log1.5(x)')
plt.plot([1, 1], [y1[0], y1[-1]], 'r--', linewidth=2)
y2 = [math.log(a, 2) for a in x]
plt.plot(x, y2, linewidth=2, color="#9F35FF", label='log2(x)')
y3 = [math.log(a, 3) for a in x]
plt.plot(x, y3, linewidth=2, color="#F75000", label='log3(x)')
plt.legend(loc='lower right')
plt.grid(True)
plt.show()
2、结果展示
3、Tylor公式计算e^x
1、介绍
下面时初等函数值在原点展开后的计算公式:
在实际中,往往需要做一些变换,可以将其分为整数部分(ln2的倍数)和小数部分,下面是e^x的计算过程:
2、代码
# @Time : 2020/12/4 21:22
# @Description :泰勒公式展开,计算e^x
import numpy as np
import math
import matplotlib as mpl
import matplotlib.pyplot as plt
def calc_e_small(x):
n = 10
b = np.array([x] * n).cumprod()
f = np.arange(1, n + 1).cumprod()
return np.sum(b / f) + 1
def calc_e(x):
reverse = False
if x < 0: # 处理负数
x = -x
reverse = True
# np.log(2)
# ln2 = 0.69314718055994530941723212145818
c = x / np.log(2)
a = int(c + 0.5)
b = x - a * np.log(2)
y = (2 ** a) * calc_e_small(b)
if reverse:
return 1 / y
return y
if __name__ == "__main__":
t1 = np.linspace(-2, 0, 10, endpoint=False)
t2 = np.linspace(0, 3, 20)
t = np.concatenate((t1, t2))
# 横轴数据
print(t)
y = np.empty_like(t)
# i= index;x= value
for i, x in enumerate(t):
y[i] = calc_e(x)
print('e^', x, ' = ', y[i], '(近似值)\t', math.exp(x), '(真实值)')
# print('误差:', y[i] - math.exp(x))
plt.figure(facecolor='w')
mpl.rcParams['font.sans-serif'] = [u'SimHei']
mpl.rcParams['axes.unicode_minus'] = False
plt.plot(t, y, 'r-', t, y, 'go', linewidth=2)
plt.title(u'Taylor展式的应用 - 指数函数', fontsize=18)
plt.xlabel('X', fontsize=15)
plt.ylabel('exp(X)', fontsize=15)
plt.grid(True, ls=':')
plt.show()
3、结果展示
4、Tylor公式计算sinx
整数部分为pi的倍数。
1、代码
# @Time : 2020/12/6 10:54
# @Description : 泰勒公式展开-sin函数
import numpy as np
import math
import matplotlib as mpl
import matplotlib.pyplot as plt
def calc_sin_small(x):
x2 = -x ** 2
t = x
f = 1
sum = 0
# 在这里完成了小数部分的转化
# 对应公式:sinx=x-x^3/(3!)+x^5/(5!)
for i in range(10):
sum += t / f
t *= x2
f *= ((2 * i + 2) * (2 * i + 3))
return sum
def calc_sin(x):
a = x / (2 * np.pi)
#
k = np.floor(a)
a = x - k * 2 * np.pi
# 对于sin(k*pi)为0,此时只剩下小数部分
return calc_sin_small(a)
if __name__ == "__main__":
t = np.linspace(-2 * np.pi, 2 * np.pi, 100, endpoint=False)
print
t # 横轴数据
y = np.empty_like(t)
for i, x in enumerate(t):
y[i] = calc_sin(x)
print
'sin(', x, ') = ', y[i], '(近似值)\t', math.sin(x), '(真实值)'
# print '误差:', y[i] - math.exp(x)
mpl.rcParams['font.sans-serif'] = [u'SimHei']
mpl.rcParams['axes.unicode_minus'] = False
plt.figure(facecolor='w')
plt.plot(t, y, 'r-', t, y, 'go', linewidth=2)
plt.title(u'Taylor展式的应用 - 正弦函数', fontsize=18)
plt.xlabel('X', fontsize=15)
plt.ylabel('sin(X)', fontsize=15)
plt.xlim((-7, 7))
plt.ylim((-1.1, 1.1))
plt.grid(True)
plt.show()
2、结果展示
5、Tylor公式计算Gini系数
1、描述
2、代码
# @Time : 2020/12/6 11:14
# @Description : 二类分类问题基尼(Gini)指数,熵之半和分类误差率的关系
import numpy as np
import matplotlib.pyplot as plt
if __name__ == "__main__":
p = np.arange(0.001, 1, 0.001, dtype=np.float)
gini = 2 * p * (1 - p)
h = -(p * np.log2(p) + (1 - p) * np.log2(1 - p)) / 2
# vstack上下合并
# 假设二分类问题中有2种类{A, B}, 共0个样本,A有3个,B有7个,
# 那么该节点的预测值为class = B; err_rate = 3 / 10 = 0.3
err = 1 - np.max(np.vstack((p, 1 - p)), axis=0)
plt.plot(p, h, 'b-', linewidth=2, label='Entropy')
plt.plot(p, gini, 'r-', linewidth=2, label='Gini')
plt.plot(p, err, 'g--', linewidth=2, label='Error')
plt.grid(True)
plt.legend(loc='upper left')
plt.show()
3、结果显示
6、阶乘和Gamma函数
1、描述
2、代码
# @Time : 2020/12/6 14:44
# @Description : 阶乘和gamma函数
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
from scipy.special import gamma
from scipy.special import factorial
mpl.rcParams['font.sans-serif'] = [u'SimHei']
mpl.rcParams['axes.unicode_minus'] = False
if __name__ == "__main__":
N = 5
x = np.linspace(0, N, 50)
# y = x!
y = gamma(x + 1)
plt.figure(facecolor='w')
plt.plot(x, y, 'r-', lw=2)
z = np.arange(0, N + 1)
f = factorial(z, exact=True) # 阶乘
#[ 1 1 2 6 24 120]
print(f)
plt.plot(z, f, 'go', markersize=8)
plt.grid(True)
plt.xlim(-0.1, N + 0.1)
plt.ylim(0.5, np.max(y) * 1.05)
plt.xlabel(u'x', fontsize=15)
plt.ylabel(u'Gamma(x)-阶乘', fontsize=15)
plt.title(u'阶乘和Gamma函数', fontsize=16)
plt.show()
3、结果展示