Python3之繪製冪函式,畫心型,math,numpy比較
阿新 • • 發佈:2019-01-28
import matplotlib
import matplotlib.pyplot as plt
import numpy
import math
from pylab import *
x = numpy.linspace(-4,4,200)
f1 = numpy.power(10,x)
f2=numpy.power(math.e,x)
f3 = numpy.power(2,x)
plt.plot(x,f1,'r',x,f2,'b',x,f3,'g',linewidth=2)
plt.axis([-4,4,-0.5,8])
plt.text(1,7.5,r'$10^x$',fontsize=16 )
plt.text(2.2,7.5,r'$e^x$',fontsize=16)
plt.text(3.2,7.5,r'$2^x$',fontsize=16)
plt.title('A simple example',fontsize=16)
savefig('power.png',dpi=75)
show()
print('\n'.join([''.join([('LoveAndy'[(x-y)%8]if((x*0.05)**2+(y*0.1)**2-1)**3-(x*0.05)**2*(y*0.1)**3<=0 else' ')for x in range(-30,30)])for y in range(15 ,-15,-1)]))
Matplotlib支援一部分Tex的排版指令,插入的公式部分由一對$符號來表示,\表空格,靠近的可以轉意,r表示該字串是一個raw String(原字串的意思) 可避免其他規則解釋字串中某些特殊的自負帶來的歧義
顯示圖形中的數學公式
import numpy as np
import matplotlib.pyplot as plt
from pylab import *
def f(x,c):
t=(2*(pi)*x)
m1 = np.sin(t)
m2 = np.exp(-c*x)
return multiply(m1,m2)
x= np.linspace(0 ,4,100)
sigma=0.5
plt.plot(x,f(x,sigma),'r',linewidth=2)
plt.xlabel(r'$\rm{time} \ t$',fontsize=16)
plt.ylabel(r'$\rm{Amplitude} \ f(x)$',fontsize=16)
plt.title(r'$f(x) \ \rm{is \ damping \ with} \ x$',fontsize=16)
plt.text(2.0,0.5,r'$f(x) = \rm {sin}(2 \pi x^2) e^{\sigma x}$',fontsize=20)
savefig('latex.png',dpi=75)
show()
比較運算速度
import time
import math
import numpy as np
x = [ i*0.001 for i in range(1000000)]
start = time.clock()
for i,t in enumerate(x):
x[i] = math.sin(t)
print("math.sin:",time.clock()-start)
x = [ i*0.001 for i in range(1000000)]
x =np.array(x)
start = time.clock()
np.sin(x,x)
print("numpy.sin:",time.clock()-start)
/ * * * * * * * 2017-08-03
from pylab import *
X = np.linspace(-np.pi,np.pi,256,endpoint=True)
C,S = np.cos(X),np.sin(X)
plot(X,C)
plot(X,S)
show()