在Python中求区间上任意函数的上下确界以计算和绘制达布和
我主要是想计算和绘制任意函数的黎曼/达布和,非常类似于以下代码:在Python中求区间上任意函数的上下确界以计算和绘制达布和,python,numpy,matplotlib,Python,Numpy,Matplotlib,我主要是想计算和绘制任意函数的黎曼/达布和,非常类似于以下代码: import numpy as np import matplotlib.pyplot as plt f = lambda x : 1/(1+x**2) a = 0; b = 5; N = 10 n = 10 # Use n*N+1 points to plot the function smoothly x = np.linspace(a,b,N+1) y = f(x) X = np.linspace(a,b,n*N+1)
import numpy as np
import matplotlib.pyplot as plt
f = lambda x : 1/(1+x**2)
a = 0; b = 5; N = 10
n = 10 # Use n*N+1 points to plot the function smoothly
x = np.linspace(a,b,N+1)
y = f(x)
X = np.linspace(a,b,n*N+1)
Y = f(X)
plt.figure(figsize=(15,5))
plt.subplot(1,3,1)
plt.plot(X,Y,'b')
x_left = x[:-1] # Left endpoints
y_left = y[:-1]
plt.plot(x_left,y_left,'b.',markersize=10)
plt.bar(x_left,y_left,width=(b-a)/N,alpha=0.2,align='edge',edgecolor='b')
plt.title('Left Riemann Sum, N = {}'.format(N))
plt.subplot(1,3,2)
plt.plot(X,Y,'b')
x_mid = (x[:-1] + x[1:])/2 # Midpoints
y_mid = f(x_mid)
plt.plot(x_mid,y_mid,'b.',markersize=10)
plt.bar(x_mid,y_mid,width=(b-a)/N,alpha=0.2,edgecolor='b')
plt.title('Midpoint Riemann Sum, N = {}'.format(N))
plt.subplot(1,3,3)
plt.plot(X,Y,'b')
x_right = x[1:] # Left endpoints
y_right = y[1:]
plt.plot(x_right,y_right,'b.',markersize=10)
plt.bar(x_right,y_right,width=-(b-a)/N,alpha=0.2,align='edge',edgecolor='b')
plt.title('Right Riemann Sum, N = {}'.format(N))
plt.show()
dx = (b-a)/N
x_left = np.linspace(a,b-dx,N)
x_midpoint = np.linspace(dx/2,b - dx/2,N)
x_right = np.linspace(dx,b,N)
print("Partition with",N,"subintervals.")
left_riemann_sum = np.sum(f(x_left) * dx)
print("Left Riemann Sum:",left_riemann_sum)
midpoint_riemann_sum = np.sum(f(x_midpoint) * dx)
print("Midpoint Riemann Sum:",midpoint_riemann_sum)
right_riemann_sum = np.sum(f(x_right) * dx)
print("Right Riemann Sum:",right_riemann_sum)
摘自
然而,我想找到的不是计算左、右和中和,而是计算上、下达布和的方法,也就是说,每个区间的上/中上和
为了实现这一点,我必须在每个区间内找到函数的下确界/上确界,但我在这里不知所措。我相信要使这一点起作用,我必须假设函数是连续的,这样下确界=最小,上确界=最大。我想我需要的不仅仅是numpy库?您可以创建一个包含所有间隔的矩阵,并将最大/最小值应用于一个长轴
import numpy as np
import matplotlib.pyplot as plt
f = lambda x : 1/(1+x**2)
a = 0; b = 5; N = 10
n = 10 # Use n*N+1 points to plot the function smoothly
x = np.linspace(a,b,N+1)
y = f(x)
X = np.linspace(a,b,n*N+1)
Y = f(X)
plt.plot(X,Y,'b')
# create offset vector with n elements, broadcast is used to enable transpose
dx = np.broadcast_to(np.linspace(0,(b-a)/N,n), (1,n)).T
# Compute all values for the offset vector (nxN matrix)
F = f(x[:-1]+dx)
y_upper = np.amax(F,0)
y_lower = np.amin(F,0)
print(y_upper)
plt.bar(x[1:],y_upper,width=-(b-a)/N,alpha=0.2,align='edge',edgecolor='b')
plt.bar(x[1:],y_lower,width=-(b-a)/N,alpha=0.2,align='edge',edgecolor='r')
plt.title('Darboux sums, N = {}'.format(N))
plt.show()