繁体   English   中英

浮点计算调试

[英]Floating point calculations debugging

因此,我最近决定学习python,并作为一项练习(加上一些有用的东西),决定制作一个Euler的Modified Method算法来求解高一阶微分方程。 输入示例为:

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

其中第一个参数是微分方程(此处:y''=-y),第二个参数是初始条件(此处:y(0)= 10,y'(0)= 0)。 然后,将其放入两个文件(x-data.txt和y-data.txt)中。

这就是问题所在:在运行具有指定代码的代码时,最后一行(在t = 1处)的读数为-0.0,但是如果您求解ODE(y = 10 * cos(x)),则其读数应为5.4。 即使您用笔和纸遍历程序并执行代码,您(和计算机)的结果也会因第二次迭代而分开。 知道是什么原因造成的吗?

注意 :我在OS X上使用python 2.7

这是我的代码:

#! /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')

当您说y_derivative=y它们是具有不同名称的SAME列表。 即,当您更改y_derivative[i]=y[i+1]两个列表都在更改。 您想使用y_derivative=y[:]制作y的副本以放入y_derivative

请参阅如何克隆或复制列表? 了解更多信息

另请参阅http://effbot.org/zone/python-list.htm

注意,通过使用您提供的示例替换sys.argv ,我可以在IDLE中调试它。 然后,如果您打开调试器并逐步执行代码,则可以看到两个列表都发生了变化。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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