python 绘制函数图像

效果1

python 绘制函数图像_第1张图片

代码

菜鸟版

import numpy as np
import math
import matplotlib.pyplot as plt

def f1(x): return 1
def f2(x): return 1/(x*x+1)
def f3(x): return math.sin(x)/(math.exp(x)+1)

plt.figure(1)
x=[]; y=[]
#生成一个等差数列,从0到10,元素数量100
a=np.linspace(0, 10, 100)
print(a)

x.clear(); y.clear()
for i in a: x.append(i), y.append(f1(i))
plt.plot(x,y)
x.clear(); y.clear()
for i in a: x.append(i), y.append(f2(i))
plt.plot(x,y)
x.clear(); y.clear()
for i in a: x.append(i), y.append(f3(i))
plt.plot(x,y)
plt.show()

进阶版

import numpy as np
import math
import matplotlib.pyplot as plt

def f1(x): return 1
def f2(x): return 1/(x*x+1)
def f3(x): return math.sin(x)/(math.exp(x)+1)

def draw(f, begin, stop, num=100, beginningPoint=True, endPoint=True):
    if not beginningPoint: begin+=(stop-begin)/num; num-=1
    x=np.linspace(begin, stop, num, endPoint); y=[]
    for i in x: y.append(f(i))
    plt.plot(x,y)

draw(f1,0,10)
draw(f2,0,10)
draw(f3,0,10)
plt.show()

效果2

python 绘制函数图像_第2张图片

代码

import numpy as np
import math
import matplotlib.pyplot as plt

def f1(x): return 2/(math.pi*math.sqrt(1-x**2))

def draw(f, begin, stop, num=100, beginningPoint=True, endPoint=True):
    if not beginningPoint: begin+=(stop-begin)/num; num-=1
    x=np.linspace(begin, stop, num, endPoint); y=[]
    for i in x: y.append(f(i))
    plt.plot(x,y)

draw(f1,0,1,endPoint=False)
plt.show()

你可能感兴趣的:(Python,数学)