#!/usr/bin/env python
# coding: utf-8
import numpy as np
from PIL import Image
if __name__ == '__main__':
image_file = 'son.png'
height = 100
img = Image.open(image_file)
img_width, img_height = img.size
width = 2 * height * img_width // img_height # 假定字符的高度是宽度的2倍
img = img.resize((width, height), Image.ANTIALIAS)
pixels = np.array(img.convert('L'))
print(pixels.shape)
print(pixels)
chars = "MNHQ$OC?7>!:-;. "
N = len(chars)
step = 256 // N
print(N)
result = ''
for i in range(height):
for j in range(width):
result += chars[pixels[i][j] // step]
result += '\n'
with open('text.txt', mode='w') as f:
f.write(result)
!/usr/bin/python
# -*- coding:utf-8 -*-
import numpy as np
from scipy import stats
import math
import matplotlib as mpl
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
import seaborn
def calc_statistics(x):
n = x.shape[0] # 样本个数
# 手动计算
m = 0
m2 = 0
m3 = 0
m4 = 0
for t in x:
m += t
m2 += t*t
m3 += t**3
m4 += t**4
m /= n
m2 /= n
m3 /= n
m4 /= n
mu = m
sigma = np.sqrt(m2 - mu*mu)
skew = (m3 - 3*mu*m2 + 2*mu**3) / sigma**3
kurtosis = (m4 - 4*mu*m3 + 6*mu*mu*m2 - 4*mu**3*mu + mu**4) / sigma**4 - 3
print('手动计算均值、标准差、偏度、峰度:', mu, sigma, skew, kurtosis)
# 使用系统函数验证
mu = np.mean(x, axis=0)
sigma = np.std(x, axis=0)
skew = stats.skew(x)
kurtosis = stats.kurtosis(x)
return mu, sigma, skew, kurtosis
if __name__ == '__main__':
d = np.random.randn(10000)
print(d)
print(d.shape)
mu, sigma, skew, kurtosis = calc_statistics(d)
print('函数库计算均值、标准差、偏度、峰度:', mu, sigma, skew, kurtosis)
# 一维直方图
mpl.rcParams['font.sans-serif'] = 'SimHei'
mpl.rcParams['axes.unicode_minus'] = False
plt.figure(num=1, facecolor='w')
y1, x1, dummy = plt.hist(d, bins=50, density=True, color='g', alpha=0.75, edgecolor='K')
t = np.arange(x1.min(), x1.max(), 0.05)
y = np.exp(-t**2 / 2) / math.sqrt(2*math.pi)
plt.plot(t, y, 'r-', lw=2)
plt.title('高斯分布,样本个数:%d' % d.shape[0])
plt.grid(True)
# plt.show()
d = np.random.randn(100000, 2)
mu, sigma, skew, kurtosis = calc_statistics(d)
print('函数库计算均值、标准差、偏度、峰度:', mu, sigma, skew, kurtosis)
# 二维图像
N = 50
density, edges = np.histogramdd(d, bins=[N, N])
print('样本总数:', np.sum(density))
density /= density.max()
x = y = np.arange(N)
print('x = ', x)
print('y = ', y)
t = np.meshgrid(x, y)
print(t)
fig = plt.figure(facecolor='w')
ax = fig.add_subplot(111, projection='3d')
ax.scatter(t[0], t[1], density, c='r', s=50*density, marker='o', depthshade=True)
# ax.plot_surface(t[0], t[1], density, cmap=cm.Accent, rstride=1, cstride=1, alpha=0.9, lw=0.75)
ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')
plt.title('二元高斯分布,样本个数:%d' % d.shape[0], fontsize=15)
plt.tight_layout(0.1)
plt.show()
# -*- coding:utf-8 -*-
# /usr/bin/python
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['axes.unicode_minus'] = False
mpl.rcParams['font.sans-serif'] = 'SimHei'
if __name__ == '__main__':
N = 5
x = np.linspace(0, N, 50)
y = gamma(x+1)
plt.figure(facecolor='w')
plt.plot(x, y, 'r-',)
plt.plot(x, y, 'mo', lw=2, ms=7)
z = np.arange(0, N+1)
print(z)
f = factorial(z, exact=True) # 阶乘
print(f)
plt.plot(z, f, 'go', markersize=9, mec='k')
plt.grid(b=True)
plt.xlim(-0.1, N+0.1)
plt.ylim(0.5, np.max(y)*1.05)
plt.xlabel('X', fontsize=15)
plt.ylabel('Gamma(X) - 阶乘', fontsize=15)
plt.title('阶乘和Gamma函数', fontsize=16)
plt.show()
#!/usr/bin/python
# -*- coding:utf-8 -*-
import numpy as np
from scipy import stats
import matplotlib as mpl
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
if __name__ == '__main__':
x1, x2 = np.mgrid[-5:5:51j, -5:5:51j]
x = np.stack((x1, x2), axis=2)
mpl.rcParams['axes.unicode_minus'] = False
mpl.rcParams['font.sans-serif'] = 'SimHei'
plt.figure(figsize=(9, 8), facecolor='w')
sigma = (np.identity(2), np.diag((3, 3)), np.diag((2, 5)), np.array(((2, 1), (1, 5))))
for i in np.arange(4):
ax = plt.subplot(2, 2, i+1, projection='3d')
norm = stats.multivariate_normal((0, 0), sigma[i])
y = norm.pdf(x)
ax.plot_surface(x1, x2, y, cmap=cm.Accent, rstride=2, cstride=2, alpha=0.9, lw=0.3, edgecolor='#303030')
ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')
plt.suptitle('二元高斯分布方差比较', fontsize=18)
plt.tight_layout(1.5)
plt.show()
meshgrid函数用于根据给定的横纵坐标点生成坐标网格,以便计算二元函数的取值。
设二维高斯函数表达式为:
#!/usr/bin/python
# -*- coding:utf-8 -*-
import numpy as np
from scipy import stats
import matplotlib as mpl
import matplotlib.pyplot as plt
import warnings
mpl.rcParams['axes.unicode_minus'] = False
mpl.rcParams['font.sans-serif'] = 'SimHei'
def calc_pearson(x, y):
std1 = np.std(x)
# np.sqrt(np.mean(x**2) - np.mean(x)**2)
std2 = np.std(y)
cov = np.cov(x, y, bias=True)[0,1]
return cov / (std1 * std2)
def intro():
N = 10
x = np.random.rand(N)
y = 2 * x + np.random.randn(N) * 0.1
print(x)
print(y)
print('系统计算:', stats.pearsonr(x, y)[0])
print('手动计算:', calc_pearson(x, y))
def rotate(x, y, theta=45):
data = np.vstack((x, y))
# print data
mu = np.mean(data, axis=1)
mu = mu.reshape((-1, 1))
# print mu
data -= mu
# print data
theta *= (np.pi / 180)
c = np.cos(theta)
s = np.sin(theta)
m = np.array(((c, -s), (s, c)))
return m.dot(data) + mu
def pearson(x, y, tip):
clrs = list('rgbmycrgbmycrgbmycrgbmyc')
plt.figure(figsize=(10, 8), facecolor='w')
for i, theta in enumerate(np.linspace(0, 90, 6)):
xr, yr = rotate(x, y, theta)
p = stats.pearsonr(xr, yr)[0]
# print calc_pearson(xr, yr)
print('旋转角度:', theta, 'Pearson相关系数:', p)
str = '相关系数:%.3f' % p
plt.scatter(xr, yr, s=40, alpha=0.9, linewidths=0.5, c=clrs[i], marker='o', label=str)
plt.legend(loc='upper left', shadow=True)
plt.xlabel('X')
plt.ylabel('Y')
plt.title('Pearson相关系数与数据分布:%s' % tip, fontsize=18)
plt.grid(b=True)
plt.show()
if __name__ == '__main__':
# warnings.filterwarnings(action='ignore', category=RuntimeWarning)
np.random.seed(0)
intro()
N = 1000
tip = '一次函数关系'
x = np.random.rand(N)
y = np.zeros(N) + np.random.randn(N)*0.001
# tip = u'二次函数关系'
# x = np.random.rand(N)
# y = x ** 2 #+ np.random.randn(N)*0.002
# tip = u'正切关系'
# x = np.random.rand(N) * 1.4
# y = np.tan(x)
# tip = u'二次函数关系'
# x = np.linspace(-1, 1, 101)
# y = x ** 2
# tip = u'椭圆'
# x, y = np.random.rand(2, N) * 60 - 30
# y /= 5
# idx = (x**2 / 900 + y**2 / 36 < 1)
# x = x[idx]
# y = y[idx]
pearson(x, y, tip)
# !/usr/bin/python
# -*- coding:utf-8 -*-
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
def triangle_wave(size, T):
t = np.linspace(-1, 1, size, endpoint=False)
# where
# y = np.where(t < 0, -t, 0)
# y = np.where(t >= 0, t, y)
y = np.abs(t)
y = np.tile(y, T) - 0.5
x = np.linspace(0, 2*np.pi*T, size*T, endpoint=False)
return x, y
def sawtooth_wave(size, T):
t = np.linspace(-1, 1, size)
y = np.tile(t, T)
x = np.linspace(0, 2*np.pi*T, size*T, endpoint=False)
return x, y
def triangle_wave2(size, T):
x, y = sawtooth_wave(size, T)
return x, np.abs(y)
def non_zero(f):
f1 = np.real(f)
f2 = np.imag(f)
eps = 1e-4
return f1[(f1 > eps) | (f1 < -eps)], f2[(f2 > eps) | (f2 < -eps)]
if __name__ == "__main__":
mpl.rcParams['font.sans-serif'] = ['simHei']
mpl.rcParams['axes.unicode_minus'] = False
np.set_printoptions(suppress=True)
x = np.linspace(0, 2*np.pi, 16, endpoint=False)
print('时域采样值:', x)
y = np.sin(2*x) + np.sin(3*x + np.pi/4) + np.sin(5*x)
# y = np.sin(x)
N = len(x)
print('采样点个数:', N)
print('\n原始信号:', y)
f = np.fft.fft(y)
print('\n频域信号:', f/N)
a = np.abs(f/N)
print('\n频率强度:', a)
iy = np.fft.ifft(f)
print('\n逆傅里叶变换恢复信号:', iy)
print('\n虚部:', np.imag(iy))
print('\n实部:', np.real(iy))
print('\n恢复信号与原始信号是否相同:', np.allclose(np.real(iy), y))
plt.figure(facecolor='w')
plt.subplot(211)
plt.plot(x, y, 'go-', lw=2)
plt.title('时域信号', fontsize=15)
plt.grid(True)
plt.subplot(212)
w = np.arange(N) * 2*np.pi / N
print('频率采样值:', w)
plt.stem(w, a, linefmt='r-', markerfmt='ro')
plt.title('频域信号', fontsize=15)
plt.grid(True)
plt.show()
# 三角/锯齿波
x, y = triangle_wave(20, 5)
# x, y = sawtooth_wave(20, 5)
N = len(y)
f = np.fft.fft(y)
# print '原始频域信号:', np.real(f), np.imag(f)
print('原始频域信号:', non_zero(f))
a = np.abs(f / N)
# np.real_if_close
f_real = np.real(f)
eps = 0.1 * f_real.max()
print('f_real = \n', f_real)
print(eps)
f_real[(f_real < eps) & (f_real > -eps)] = 0
f_imag = np.imag(f)
eps = 0.3 * f_imag.max()
print(eps)
f_imag[(f_imag < eps) & (f_imag > -eps)] = 0
f1 = f_real + f_imag * 1j
y1 = np.fft.ifft(f1)
y1 = np.real(y1)
# print '恢复频域信号:', np.real(f1), np.imag(f1)
print('恢复频域信号:', non_zero(f1))
plt.figure(figsize=(8, 8), facecolor='w')
plt.subplot(311)
plt.plot(x, y, 'g-', lw=2)
plt.title('三角波', fontsize=15)
plt.grid(True)
plt.subplot(312)
w = np.arange(N) * 2*np.pi / N
plt.stem(w, a, linefmt='r-', markerfmt='ro')
plt.title('频域信号', fontsize=15)
plt.grid(True)
plt.subplot(313)
plt.plot(x, y1, 'b-', lw=2, markersize=4)
plt.title('三角波恢复信号', fontsize=15)
plt.grid(True)
plt.tight_layout(1.5, rect=[0, 0.04, 1, 0.96])
plt.suptitle('快速傅里叶变换FFT与频域滤波', fontsize=17)
plt.show()
#!/usr/bin/python
# -*- coding:utf-8 -*-
import numpy as np
import os
from PIL import Image
import matplotlib.pyplot as plt
import matplotlib as mpl
from pprint import pprint
def restore1(sigma, u, v, K): # 奇异值、左特征向量、右特征向量
m = len(u)
n = len(v[0])
a = np.zeros((m, n))
for k in range(K):
uk = u[:, k].reshape(m, 1)
vk = v[k].reshape(1, n)
a += sigma[k] * np.dot(uk, vk)
a[a < 0] = 0
a[a > 255] = 255
# a = a.clip(0, 255)
return np.rint(a).astype('uint8')
def restore2(sigma, u, v, K): # 奇异值、左特征向量、右特征向量
m = len(u)
n = len(v[0])
a = np.zeros((m, n))
for k in range(K+1):
for i in range(m):
a[i] += sigma[k] * u[i][k] * v[k]
a[a < 0] = 0
a[a > 255] = 255
return np.rint(a).astype('uint8')
if __name__ == "__main__":
A = Image.open(".\\son.png", 'r')
print(A)
output_path = r'.\SVD_Output'
if not os.path.exists(output_path):
os.mkdir(output_path)
a = np.array(A)
print(a.shape)
K = 50
u_r, sigma_r, v_r = np.linalg.svd(a[:, :, 0])
u_g, sigma_g, v_g = np.linalg.svd(a[:, :, 1])
u_b, sigma_b, v_b = np.linalg.svd(a[:, :, 2])
plt.figure(figsize=(11, 9), facecolor='w')
mpl.rcParams['font.sans-serif'] = ['simHei']
mpl.rcParams['axes.unicode_minus'] = False
for k in range(1, K+1):
print(k)
R = restore1(sigma_r, u_r, v_r, k)
G = restore1(sigma_g, u_g, v_g, k)
B = restore1(sigma_b, u_b, v_b, k)
I = np.stack((R, G, B), axis=2)
Image.fromarray(I).save('%s\\svd_%d.png' % (output_path, k))
if k <= 12:
plt.subplot(3, 4, k)
plt.imshow(I)
plt.axis('off')
plt.title('奇异值个数:%d' % k)
plt.suptitle('SVD与图像分解', fontsize=20)
plt.tight_layout(0.3, rect=(0, 0, 1, 0.92))
# plt.subplots_adjust(top=0.9)
plt.show()
#!/usr/bin/python
# -*- coding:utf-8 -*-
import numpy as np
import os
from PIL import Image
import matplotlib.pyplot as plt
import matplotlib as mpl
from pprint import pprint
def restore1(sigma, u, v, K): # 奇异值、左特征向量、右特征向量
m = len(u)
n = len(v[0])
a = np.zeros((m, n))
for k in range(K):
uk = u[:, k].reshape(m, 1)
vk = v[k].reshape(1, n)
a += sigma[k] * np.dot(uk, vk)
a[a < 0] = 0
a[a > 255] = 255
# a = a.clip(0, 255)
return np.rint(a).astype('uint8')
def restore2(sigma, u, v, K): # 奇异值、左特征向量、右特征向量
m = len(u)
n = len(v[0])
a = np.zeros((m, n))
for k in range(K+1):
for i in range(m):
a[i] += sigma[k] * u[i][k] * v[k]
a[a < 0] = 0
a[a > 255] = 255
return np.rint(a).astype('uint8')
if __name__ == "__main__":
A = Image.open(".\\son.png", 'r')
print(A)
output_path = r'.\SVD_Output'
if not os.path.exists(output_path):
os.mkdir(output_path)
a = np.array(A)
print(a.shape)
K = 50
u_r, sigma_r, v_r = np.linalg.svd(a[:, :, 0])
u_g, sigma_g, v_g = np.linalg.svd(a[:, :, 1])
u_b, sigma_b, v_b = np.linalg.svd(a[:, :, 2])
plt.figure(figsize=(11, 9), facecolor='w')
mpl.rcParams['font.sans-serif'] = ['simHei']
mpl.rcParams['axes.unicode_minus'] = False
for k in range(1, K+1):
print(k)
R = restore1(sigma_r, u_r, v_r, k)
G = restore1(sigma_g, u_g, v_g, k)
B = restore1(sigma_b, u_b, v_b, k)
I = np.stack((R, G, B), axis=2)
Image.fromarray(I).save('%s\\svd_%d.png' % (output_path, k))
if k <= 12:
plt.subplot(3, 4, k)
plt.imshow(I)
plt.axis('off')
plt.title('奇异值个数:%d' % k)
plt.suptitle('SVD与图像分解', fontsize=20)
plt.tight_layout(0.3, rect=(0, 0, 1, 0.92))
# plt.subplots_adjust(top=0.9)
plt.show()
# !/usr/bin/python
# -*- coding:utf-8 -*-
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
if __name__ == "__main__":
stock_max, stock_min, stock_close, stock_amount = np.loadtxt('.\\SH600000.txt', delimiter='\t', skiprows=2, usecols=(2, 3, 4, 5), unpack=True)
N = 100
stock_close = stock_close[:N]
print(stock_close)
n = 10
weight = np.ones(n)
weight /= weight.sum()
print(weight)
stock_sma = np.convolve(stock_close, weight, mode='valid') # simple moving average
weight = np.linspace(1, 0, n)
weight = np.exp(weight)
weight /= weight.sum()
print(weight)
stock_ema = np.convolve(stock_close, weight, mode='valid') # exponential moving average
t = np.arange(n-1, N)
poly = np.polyfit(t, stock_ema, 10)
print(poly)
stock_ema_hat = np.polyval(poly, t)
mpl.rcParams['font.sans-serif'] = ['SimHei']
mpl.rcParams['axes.unicode_minus'] = False
plt.figure(facecolor='w')
plt.plot(np.arange(N), stock_close, 'ro-', linewidth=2, label='原始收盘价')
t = np.arange(n-1, N)
plt.plot(t, stock_sma, 'b-', linewidth=2, label='简单移动平均线')
plt.plot(t, stock_ema, 'g-', linewidth=2, label='指数移动平均线')
plt.legend(loc='upper right')
plt.title('股票收盘价与滑动平均线MA', fontsize=15)
plt.grid(True)
# plt.show()
print(plt.figure(figsize=(8.8, 6.6), facecolor='w'))
plt.plot(np.arange(N), stock_close, 'ro-', linewidth=1, label='原始收盘价')
plt.plot(t, stock_ema, 'g-', linewidth=2, label='指数移动平均线')
plt.plot(t, stock_ema_hat, '-', color='#FF4040', linewidth=3, label='指数移动平均线估计')
plt.legend(loc='upper right')
plt.title('滑动平均线MA的估计', fontsize=15)
plt.grid(True)
plt.show()
#!/usr/bin/python
# -*- coding:utf-8 -*-
import numpy as np
import os
from PIL import Image
def convolve(image, weight):
height, width = image.shape
h, w = weight.shape
height_new = height - h + 1
width_new = width - w + 1
image_new = np.zeros((height_new, width_new), dtype=np.float)
for i in range(height_new):
for j in range(width_new):
image_new[i,j] = np.sum(image[i:i+h, j:j+w] * weight)
image_new = image_new.clip(0, 255)
image_new = np.rint(image_new).astype('uint8')
return image_new
# image_new = 255 * (image_new - image_new.min()) / (image_new.max() - image_new.min())
if __name__ == "__main__":
A = Image.open(".\\son.png", 'r')
output_path = '.\\ImageConvolve\\'
if not os.path.exists(output_path):
os.mkdir(output_path)
a = np.array(A)
avg3 = np.ones((3, 3))
avg3 /= avg3.sum()
avg5 = np.ones((5, 5))
avg5 /= avg5.sum()
gauss = np.array(([0.003, 0.013, 0.022, 0.013, 0.003],
[0.013, 0.059, 0.097, 0.059, 0.013],
[0.022, 0.097, 0.159, 0.097, 0.022],
[0.013, 0.059, 0.097, 0.059, 0.013],
[0.003, 0.013, 0.022, 0.013, 0.003]))
soble_x = np.array(([-1, 0, 1], [-2, 0, 2], [-1, 0, 1]))
soble_y = np.array(([-1, -2, -1], [0, 0, 0], [1, 2, 1]))
soble = np.array(([-1, -1, 0], [-1, 0, 1], [0, 1, 1]))
prewitt_x = np.array(([-1, 0, 1], [-1, 0, 1], [-1, 0, 1]))
prewitt_y = np.array(([-1, -1,-1], [0, 0, 0], [1, 1, 1]))
prewitt = np.array(([-2, -1, 0], [-1, 0, 1], [0, 1, 2]))
laplacian4 = np.array(([0, -1, 0], [-1, 4, -1], [0, -1, 0]))
laplacian8 = np.array(([-1, -1, -1], [-1, 8, -1], [-1, -1, -1]))
weight_list = ('avg3', 'avg5', 'gauss', 'soble_x', 'soble_y', 'soble', 'prewitt_x', 'prewitt_y', 'prewitt', 'laplacian4', 'laplacian8')
print('梯度检测:')
for weight in weight_list:
print(weight, 'R', end=' ')
R = convolve(a[:, :, 0], eval(weight))
print('G', end=' ')
G = convolve(a[:, :, 1], eval(weight))
print('B')
B = convolve(a[:, :, 2], eval(weight))
I = np.stack((R, G, B), 2)
Image.fromarray(I).save(output_path + weight + '.png')
# # X & Y
# print '梯度检测XY:'
# for w in (0, 2):
# weight = weight_list[w]
# print weight, 'R',
# R = convolve(a[:, :, 0], eval(weight))
# print 'G',
# G = convolve(a[:, :, 1], eval(weight))
# print 'B'
# B = convolve(a[:, :, 2], eval(weight))
# I1 = np.stack((R, G, B), 2)
#
# weight = weight_list[w+1]
# print weight, 'R',
# R = convolve(a[:, :, 0], eval(weight))
# print 'G',
# G = convolve(a[:, :, 1], eval(weight))
# print 'B'
# B = convolve(a[:, :, 2], eval(weight))
# I2 = np.stack((R, G, B), 2)
#
# I = 255 - np.maximum(I1, I2)
# Image.fromarray(I).save(output_path + weight[:-2] + '.png')
#!/usr/bin/python
# -*- coding:utf-8 -*-
from scipy.integrate import odeint
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
def lorenz(state, t):
# print w
# print t
sigma = 10
rho = 28
beta = 3
x, y, z = state
return np.array([sigma*(y-x), x*(rho-z)-y, x*y-beta*z])
def lorenz_trajectory(s0, N):
sigma = 10
rho = 28
beta = 8/3.
delta = 0.001
s = np.empty((N+1, 3))
s[0] = s0
for i in np.arange(1, N+1):
x, y, z = s[i-1]
a = np.array([sigma*(y-x), x*(rho-z)-y, x*y-beta*z])
s[i] = s[i-1] + a * delta
return s
if __name__ == "__main__":
mpl.rcParams['font.sans-serif'] = ['SimHei']
mpl.rcParams['axes.unicode_minus'] = False
# Figure 1
s0 = (0., 1., 0.)
t = np.arange(0, 30, 0.01)
s = odeint(lorenz, s0, t)
plt.figure(figsize=(12, 8), facecolor='w')
plt.subplot(121, projection='3d')
plt.plot(s[:, 0], s[:, 1], s[:, 2], c='g')
plt.title('微分方程计算结果', fontsize=16)
s = lorenz_trajectory(s0, 40000)
plt.subplot(122, projection='3d')
plt.plot(s[:, 0], s[:, 1], s[:, 2], c='r')
plt.title('沿着梯度累加结果', fontsize=16)
plt.tight_layout(1, rect=(0,0,1,0.98))
plt.suptitle('Lorenz系统', fontsize=20)
plt.show()
# Figure 2
ax = Axes3D(plt.figure(figsize=(8, 8)))
s0 = (0., 1., 0.)
s1 = lorenz_trajectory(s0, 50000)
s0 = (0., 1.0001, 0.)
s2 = lorenz_trajectory(s0, 50000)
# 曲线
ax.plot(s1[:, 0], s1[:, 1], s1[:, 2], c='g', lw=0.4)
ax.plot(s2[:, 0], s2[:, 1], s2[:, 2], c='r', lw=0.4)
# 起点
ax.scatter(s1[0, 0], s1[0, 1], s1[0, 2], c='g', s=50, alpha=0.5)
ax.scatter(s2[0, 0], s2[0, 1], s2[0, 2], c='r', s=50, alpha=0.5)
# 终点
ax.scatter(s1[-1, 0], s1[-1, 1], s1[-1, 2], c='g', s=100)
ax.scatter(s2[-1, 0], s2[-1, 1], s2[-1, 2], c='r', s=100)
ax.set_title('Lorenz方程与初始条件', fontsize=20)
ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')
plt.show()
# /usr/bin/python
# -*- coding:utf-8 -*-
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.cm as cm
def divergent(c):
z = 0
i = 0
while i < 100:
z = z**2 + c
if abs(z) > 2:
break
i += 1
return i
def draw_mandelbrot(center_x, center_y, size):
x1, x2 = center_x - size, center_x + size
y1, y2 = center_y - size, center_y + size
x, y = np.mgrid[x1:x2:500j, y1:y2:500j]
c = x + y * 1j
divergent_ = np.frompyfunc(divergent, 1, 1)
mandelbrot = divergent_(c)
mandelbrot = mandelbrot.astype(np.float64) # ufunc返回PyObject数组
print(size, mandelbrot.max(), mandelbrot.min())
plt.pcolormesh(x, y, mandelbrot, cmap=cm.jet)
plt.xlim((np.min(x), np.max(x)))
plt.ylim((np.min(y), np.max(y)))
plt.savefig(str(size)+'.png')
# plt.show()
if __name__ == '__main__':
draw_mandelbrot(0, 0, 2)
interested_x = 0.33987
interested_y = -0.575578
interested_x, interested_y = 0.27322626, 0.595153338
for size in np.logspace(0, -3, 4, base=10):
print(size)
draw_mandelbrot(interested_x, interested_y, size)