简体   繁体   中英

Name Error., While solving Coupled Differential equation by 4th order Runge kutta algorithm

The code is to solve the Coupled differential equation by using Runge - Kutta algorithm the code looks fine but It is showing, Name error.

from math import *
x0=float(input('Enter the Iv for x '))
y0=float(input('Enter the corresponding y value'))
z0=float(input('Enter the corrsponding z value'))
print(x0,y0,z0)
A=input('dy/dx = f(x,y,z) =')
B=input('dz/dx = g(x,y,z) =')
def  f(x0,y0,z0):
  return(eval(A))
def g(x0,y0,z0):
  return(eval(B))
stp=float(input('Enter Step Size'))
z=int(input('Enter number of iteration'))
for i in range(1,z+1):
  k1=stp*f(x0,y0,z0)
  print(k1)
  l1=stp*g(x0,y0,z0)
  k2=stp*f(x0+.5*stp,y0+.5*k1,z0+.5*l1)
  l2=stp*g(x0+.5*stp,y0+.5*k1,z0+.5*l1)
  k3=stp*f(x0+.5*stp,y0+.5*k2,z0+.5*l2)
  l3=stp*g(x0+.5*stp,y0+.5*k2,z0+.5*l2)
  k4=stp*f(x0+stp,y0+k3,z0+l3)
  l4=stp*g(x0+stp,y0+k3,z0+l3)
  y1=y0+(k1+k4+2*(k2+k3))/6
  z1=z0+(l1+l4+2*(l2+l3))/6
  print('Value of y',i,"=",y1)
  print('Value of z',i,"=",z1)
  x0=x0+stp
  y0=y1
  z0=z0+stp
  z0=z1

The image Shows The error that I am getting

y is not defined in your function scope for neither f nor g so when eval(A) and eval(B) are called, they cannot find y and z in the function space (nor the global) so if you rename the arguments for f and g to match how your input prompt presents them, they should be found by eval. That is,

def f(x, y, z):
    return eval(A)

or

def f(x0, y0, z0):
    return eval(A, {'x': x0, 'y': y0, 'z': z0})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM