본문 바로가기
파이썬

파이썬 Python UnboundLocalError에 대한 도움말 : 할당 전에 참조 된 지역 변수

by º기록 2021. 1. 14.
반응형

나는 전에 비슷한 질문을 게시했지만, 나는 내 질문을 잘못 해석했을 수 있으므로 여기에 내 원본 코드를 게시하고 누군가 나를 도울 수있는 사람을 찾으면 정말 갇혀 있습니다 .. 정말 고마워요.

from numpy import *
import math as M

#initial condition  All in SI unit
G=6.673*10**-11   #Gravitational constant
ms=1.9889*10**30 #mass of the sun
me=5.9742*10**24 #mass of the earth
dt=10           #time step
#Creat arrays
vs=array([[0,0,0]])     #1st element stand for x component of V of earth
ve=array([[29770,0,0]])
rs=array([[0,0,0]])           
re=array([[0,1.4960*10**11,0]])

#First update velocity in order to start leapfrog approximation
fs=-G*ms*me*((rs-re)/(M.sqrt((rs-re)[0][0]**2+(rs-re)[0][1]**2+(rs-re)[0][2]**2))**3)
fe=-fs
vs=vs+fs*dt/ms 
ve=ve+fe*dt/me

n=input('please enter the number of timestep you want it evolve:')
#update force
def force(n,ms,me,rs,re,G):
    rs,re=update_r(rs,re,n,dt)
    fs=-G*ms*me*((rs-re)/(M.sqrt((rs-re)[0][0]**2+(rs-re)[0][1]**2+(rs-re)[0][2]**2))**3)
    fe=-fs
    return fs,fe

#update velocities
def update_v(n,vs,ve,ms,me,dt,fs,fe):
    fs,fe=force(n,ms,me,rs,re,G)
    i=arange(n)
    vs=vs+fs[:]*i[:,newaxis]*dt/ms
    ve=ve+fe[:]*i[:,newaxis]*dt/me
    return vs,ve

#update position
def update_r(rs,re,n,dt):
    vs,ve=update_v(n,vs,ve,ms,me,dt,fs,fe)
    i=arange(n)
    rs=rs+vs[:]*i[:,newaxis]*dt
    re=re+ve[:]*i[:,newaxis]*dt
    return rs,re
#there is start position,v,r,f all have initial arrays(when n=0).
#then it should calculate f(n=1) then use this to update v(n=0)
#to v(n=1),then use v(n=1) update r(n=0) to r(n=1),then use r(n=1)
#update f(n=1) to f(n=2)....and so on until finish n.but this code seems doesnt do this,,how can I make it? – 

내가 포스 파이썬을 호출하면 다음을 제공합니다.

please enter the number of timestep you want it evolve:4Traceback (most recent call last):
  File "<pyshell#391>", line 1, in <module>
    force(n,ms,me,rs,re,G)
  File "/Users/Code.py", line 24, in force
    rs,re=update_r(rs,re,n,dt)
  File "/Users/Code.py", line 39, in update_r
    vs,ve=update_v(n,vs,ve,ms,me,dt,fs,fe)
UnboundLocalError: local variable 'vs' referenced before assignment

누구에게 팁을 줄 수 있습니까? 감사합니다 ......

 

해결 방법

 

update_r 의 첫 번째 줄에는 vs, ve = update_v (n, vs, ve, ms, me, dt, fs, fe) 가 있습니다. 호출중인 함수를보십시오. 여러 매개 변수를 사용하여 update_v 를 호출하고 있습니다. 이러한 매개 변수 중 하나는 vs 입니다. 그러나 해당 함수에서 vs 가 나타나는 것은 이번이 처음입니다. vs 변수에 아직 연결된 값이 없습니다. 먼저 초기화를 시도하면 오류가 사라집니다.

 

참조 페이지 https://stackoverflow.com/questions/1735263

 

 

반응형

댓글