2014-11-23 98 views
0

我对python非常陌生,并且试图使用梯形法则来逼近4个函数的整体,然后找到这个和plot的错误,错误VS用于条数,NTypeError:只能将长度为1的数组转换为Python标量

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

回答

1

你传递N1这是一个名为Nerror数组,然后将它传递给TrapRule,但它仍然是一个数组。

因此该行:

for i in range (1, N-1) 

实际上是

for i in range(1, np.arange (10, 100, 1)-1) 

不作任何意义。

什么,你可能会试图做一个猜测是:

N1 = np.arange (10, 100, 1) 

errors = [error(F1, f1, N) for N in N1] # make a vector of errors, one error value each N1 value 

plt.plot(N1, errors, 'g') 
plt.show() 

enter image description here

+0

好,并且这是为什么不允许? (对不起,我有点绝望) – 2014-11-23 17:45:38

+0

'范围'给出的范围是两个整数。整数和数组之间的范围是什么意思? – tom10 2014-11-23 17:47:23

+0

哦,谢谢:D,所以我需要改变安排,但要编号?我可以这样做吗?还是我需要一个全新的方法? – 2014-11-23 17:54:10

相关问题