2014-11-23 2 views
0

저는 파이썬을 처음 접했을 때 사다리꼴 규칙을 사용하여 4 개의 함수를 근사화 한 다음이 점과 플로트의 오류를 찾습니다. 사용되는 스트립의 번호 대 오류, N. 나는 오류의 프로그램을 실행하면TypeError : 길이가 1 인 배열 만 파이썬 스칼라로 변환 될 수 있습니다

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 당신은 N1을 전달하는

답변

1

입니다 N이라는 이름으로 error에 배열 한 다음 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

좋아, 왜 허용되지 않음 :

당신이 시도 될 수 무슨 추측은? (미안하지만 좀 이상하다) –

+0

'range'는 범위가 두 개의 정수가된다. 정수와 배열 사이의 범위는 무엇을 의미합니까? – tom10

+0

오 감사합니다 : D 그래서 내가 배열을 변경해야하지만, 번호? 나는 그것을 할 수 있습니까? 아니면 완전히 새로운 접근이 필요합니까? –

관련 문제