我是python的新手,我正在尝试使用梯形规则来近似4个函数的积分,然后找出错误,这个和图,错误与使用的条带的数量,N。
import numpy as np
import pylab as plt
#creating functions of the functions
def f1(x):
'''this is a function to return f1 = e^(-4x)cos(8*pi*x)'''
return (np.exp(-4*x))*np.cos(8*np.pi*x)
def f2(x):
'''this is a function to return f2 = (cos(2*pi*x))^2'''
return (np.cos(2*np.pi*x))**2
def f3(x):
'''this is a function to return f3 = sin(2*pi*x)'''
return np.sin(2*np.pi*x)
def f4(x):
'''this is a function to return f4 = e^(-((x-5)^2)/0.04)'''
a = x-.5
b = a*a
c = -b
return np.exp(c/.04)
x = np.arange (0.0,1.0,0.01)
#plt.figure(1)
#plt.plot(x, f1(x), 'g-', x, f2(x), 'r--', x, f3(x), 'k--', x, f4(x), 'b--')
#plt.show()
# N is the number of strips
a=0.0
b= 1
def TrapRule(f,a,b, N):
'''this a function that appoximates the intregrals of a funtion between
0 and 1, using the Trapezoidal rule and returns the appoximate value.'''
#for N in range (3,15):
H=(b-a)/(N)
x=H
c=0.0
for i in range (1, N-1):
c += 2*f(x)
x += H
print (H/2)*(f(a)+f(b)+ c)
return (H/2)*(f(a)+f(b)+ c)
z=np.pi
a= 16*z**2
b= 4+a
c= 1/b
d= np.exp(4)
e=1/d
f= 1-e
F1 = c*f
F2= 0.5
F3 = 0
F4 = 0.199918*((np.pi)**0.5)
#print F1
#TrapRule(f1, .0, 1. , 20000)
#print F2
#TrapRule(f2, .0, 1. , 20000)
#print F3
#TrapRule(f3, .0, 1. , 20000)
#print F4
#TrapRule(f4, .0, 1. , 20000)
def error(F, f, N): #works
'''this function caluclate the error from using the TrapRule (compared with real answer)'''
A = F - TrapRule(f, .0, 1. , N)
B = A/F
Er = B*100
#print Er
return Er
N1 = np.arange (10, 100, 1)
plt.plot(N1, error(F1, f1, N1), 'g')
plt.show()
当我运行程序时得到错误,
Traceback (most recent call last):
File "C:\Users\mem208\Portable Python 2.7.6.1\ComAss.py", line 97, in <module>
plt.plot(N1, error(F1, f1, N1), 'g')
File "C:\Users\mem208\Portable Python 2.7.6.1\ComAss.py", line 88, in error
A = F - TrapRule(f, .0, 1. , N)
File "C:\Users\mem208\Portable Python 2.7.6.1\ComAss.py", line 53, in TrapRule
for i in range (1, N-1):
TypeError: only length-1 arrays can be converted to Python scalars
谢谢:D
答案 0 :(得分:1)
您将N1
数组传递到名为error
的{{1}},然后将其传递给N
,但它仍然是一个数组。
因此行:
TrapRule
实际上是
for i in range (1, N-1)
这没有任何意义。
猜测你可能要做的是:
for i in range(1, np.arange (10, 100, 1)-1)