python中割线方法的循环编写问题

2024-05-01 22:05:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我最近开始学习python,课程中的一个问题是编写割线方法。我无法重新分配循环中的变量。你知道吗

不管我怎么写while语句,我总是得到被零除的错误。我假设这是因为我的代码将循环设为当前x_1=x_0并进行计算 f(x_1)-f(x_0),而不是将旧的x_1用于x_0。 我的尝试:

G = 6.6741*10**-11
r_e = 6371000
r_m = 1737100
M_e = 5.9722*10**24
M_m = 7.3420*10**22
R = 3.8440*10**8
w =  2.6617*10**-6

def f(x):
    return (G*M_e)/x**2 - (G*M_m)/(R-x)**2 - w**2 * x

x_0=2*10**8
x_1=2.2*10**8

i=1

while i<=10 or 0.99 < x_1/x_0 <1.01:
    x_1=float(x_1-f(x_1)*(x_1-x_0)/(f(x_1)-f(x_0)))
    i = i+1
    x_0=x_1

print (x_1)

错误:

runfile('//myfiles/vj284/dos/python/Coursework q1.py', 
wdir='//myfiles/vj284/dos/python')
Traceback (most recent call last):

  File "<ipython-input-2-b33827a1b929>", line 1, in <module>
    runfile('//myfiles/vj284/dos/python/Coursework q1.py', 
wdir='//myfiles/vj284/dos/python')

   File "C:\Program Files\Anaconda3\lib\site- 
packages\spyder\utils\site\sitecustomize.py", line 705, in runfile
    execfile(filename, namespace)

  File "C:\Program Files\Anaconda3\lib\site- 
packages\spyder\utils\site\sitecustomize.py", line 102, in execfile
    exec(compile(f.read(), filename, 'exec'), namespace)

  File "//myfiles/vj284/dos/python/Coursework q1.py", line 20, in <module>
    x_1=float(x_1-f(x_1)*(x_1-x_0)/(f(x_1)-f(x_0)))

ZeroDivisionError: float division by zero

Tags: inpy错误linesitefloatfilewhile
1条回答
网友
1楼 · 发布于 2024-05-01 22:05:58

I am assuming this is because my code is making the loops current x_1=x_0 and computing f(x_1)-f(x_0), rather than using the old x_1 for x_0.

没有。这是因为循环中的最后一行x_0 = x_1。为什么要覆盖x_0?还有,什么是y?你知道吗

编辑:由于添加了文本版本,因此更容易修复代码。只需使用一个临时变量来保存“new”结果。另外,将or更改为and,并添加一个条件来检查收敛性(如果方法收敛x_0将与x_1相同,因此代码将由于被零除而崩溃):

i = 1
while i <= 10 and 0.99 < x_1/x_0 <1.01 and abs((x_1 - x_0) / x_1) > 1e-15: :
    tmp = x_1 - f(x_1) * (x_1 - x_0) / (f(x_1) - f(x_0))
    i = i + 1
    x_0 = x_1
    x_1 = tmp

不清楚为什么循环条件中有and 0.99 < x_1/x_0 <1.01。我想你应该把它去掉:

i = 1
while i <= 10 and abs(x_1 - x_0) > 1e-15 * abs(x_1):
    tmp = x_1 - f(x_1) * (x_1 - x_0) / (f(x_1) - f(x_0))
    i = i + 1
    x_0 = x_1
    x_1 = tmp

最后一次编辑:为了避免使用临时变量,我将重写循环如下:

for _ in range(10):
    if abs(x_1 - x_0) < 1e-15 * abs(x_1):  
        break  
    x_0, x_1 = x_1, x_1 - f(x_1) * (x_1 - x_0) / (f(x_1) - f(x_0)) 

此外,您可能应该检查函数值的接近性,而不是它的参数:通常,由于舍入错误,f(x_1)可能等于f(x_0),即使x_1 != x_0。或者,您可能希望检查f(x_1) <= eps是否指示找到了根。你知道吗

相关问题 更多 >