Вопрос

So I recently decided to learn python and as a exercise (plus making something useful) I decided to make a Euler's Modified Method algorithm for solving higher-then-first order differential equations. An example input would be:

python script_name.py -y[0] [10,0]

where the first argument is the deferential equation (here: y''=-y), and the second one the initial conditions (here: y(0)=10, y'(0)=0). It is then meant to out put the resusts to two files (x-data.txt, and y-data.txt).

Heres the problem: When in run the code with the specified the final line (at t=1) reads -0.0, but if you solve the ODE (y=10*cos(x)), it should read 5.4. Even if you go through the program with a pen and paper and execute the code, your (and the computers) results apart to diverge by the second iteration). Any idea what could have caused this?

NB: I'm using python 2.7 on a os x

Here's my code:

#! /usr/bin/python
# A higher order differential equation solver using Euler's Modified Method

import math
import sys

step_size = 0.01
x=0
x_max=1

def derivative(x, y):
    d = eval(sys.argv[1])
    return d

y=eval(sys.argv[2])
order = len(y)
y_derivative=y

xfile = open('x-data.txt','w+')
yfile = open('y-data.txt','w+')

while (x<x_max):
    xfile.write(str(x)+"\n")
    yfile.write(str(y[0])+"\n")

    for i in range(order-1):
        y_derivative[i]=y[(i+1)]
    y_derivative[(order-1)] =  derivative(x,y)

    for i in range(order):
        y[i]=y[i]+step_size*y_derivative[i]
    x=x+step_size


xfile.close()
yfile.close()

print('done')
Это было полезно?

Решение

When you say y_derivative=y they are the SAME list with different names. I.e. when you change y_derivative[i]=y[i+1] both lists are changing. You want to use y_derivative=y[:] to make a copy of y to put in y_derivative

See How to clone or copy a list? for more info

Also see http://effbot.org/zone/python-list.htm

Note, I was able to debug this in IDLE by replacing sys.argv with your provided example. Then if you turn on the debugger and step through the code, you can see both lists change.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top