有人熟悉穆勒算法吗?在编程上遇到问题。

0 投票
1 回答
1575 浏览
提问于 2025-04-17 17:57

我在使用穆勒算法的代码时遇到了一些问题,这个课程只涉及基础的Python编程。我的程序还没有处理像输出中那样的虚数,而且我的停止条件也没有正常工作,但现在我最关心的是如何正确打印下面输出中的数字。我把输出作为代码贴上来,因为我刚来这个网站,系统一直提示我“代码格式不正确”,所以我有点困惑。

非常感谢任何帮助!

When f=(x-5)*(x-4)*(x+7)
and initial guesses are 1,3,and -10 
and tolerance = 0.000001

The output of this code should look like this:
The initial estimates to the root are:
f( 1 )= 96
f( 3 )= 20
f( -10 )= -630
0 : estimate to the root is f( 1 )= 96

1 : estimate to the root is f( (-4.102012878968893+0j) )= (213.71097514696675+0j)  

2 : estimate to the root is f( (3.463202253458595+0j) )= (8.63161417086553+0j)

3 : estimate to the root is f( (3.6797449479714586+0j) )= (4.515592141362759+0j) 

4 : estimate to the root is f( (3.9234514667540585+0j) )= (0.9001820953746444+0j)

5 : estimate to the root is f( (3.9988300605239253+0j) )= (0.012883020219233893+0j)

6 : estimate to the root is f( (3.9999973985379675+0j) )= (2.861615003307639e-05+0j)

The approximation to the root is f( (3.999999999978821+0j) ) = (2.329696435810382e-
10+0j)

这是我的实际代码:

import string
from math import *
from cmath import *

def evalFunction(f,x):
    x=eval(f)
    return x

def main():
    f= input("Input the function: ")
    p0=eval(input("Input the first estimate to the root of the function: "))
    p1=eval(input("Input the second estimate to the root of the function: "))
    p2=eval(input("Input the third estimate to the root of the function: "))
    t=eval(input("Enter the tolerance "))

    fp0=evalFunction(f,p0)
    fp1=evalFunction(f,p1)
    fp2=evalFunction(f,p2)

    print("The initial estimates to the root are:")
    print("f(",p0,")=",fp0)
    print("f(",p1,")=",fp1)
    print("f(",p2,")=",fp2)
    count=0
    print(count,": estimate to the root is f(",p0,")=",fp0)
    fp3=1

    while count<30:
        while (abs(fp3))>=t:
            fp0=evalFunction(f,p0)
            fp1=evalFunction(f,p1)
            fp2=evalFunction(f,p2)


            #Computes a,b,c 
            o=fp1-fp2
            n=fp0-fp2
            s=p1-p2
            r=p0-p2
            denom=r*s*(p0-p1)
            a=(s*n-r*o)/denom
            b=((r**2)*o-(s**2)*n)/denom
            c=fp2
            print()

            count=count+1

            #Computes the roots
            x1= (-2*c)/(b+(b**2-4*a*c)**.5)
            x2=(-2*c)/(b-(b**2-4*a*c)**.5)

            if b>0:
                p3= p2+x1
                fp3=evalFunction(f,p3)
                print(count,": estimate to the root is f(",p3,")=",fp3)
                print()

            else:
                p3= p2+x2
                fp3=evalFunction(f,p3)
                print(count,": estimate to the root is f(",p3,")=",fp3)
                print()

            p2=p3        

main()

1 个回答

1

不太清楚你程序的哪个部分出现了问题,可能是因为当满足容差条件后,代码就卡住了。因为在内层循环中,count 是在不断增加的,而一旦满足容差条件,内层循环就不再执行了,这样外层循环 while count<30: 就会一直运行下去。

不过,把 while count<30:while (abs(fp3))>=t: 改成 while count<30 and (abs(fp3))>=t: 就能解决这个问题。最后还有一条说明,关于 p0p1 在循环中没有更新的问题,这可能会影响收敛速度。

关于输出格式,可以看看下面代码中使用的 format 函数。注意,在这段代码中,我在大多数等号周围加了空格,以便更容易阅读,并且通过命令行输入参数。没有在命令行输入的参数仍然会被提示输入。我不确定在 Windows 系统上命令行参数是否以相同的方式被识别。

另外,你可以用不同或相同的小数位数来打印数字的实部和虚部;例如,c=3-5j; d=4.4+5.5j; print ('d: {.real:7.2f} {.imag:+.3f}j c: {:9.4f}'.format(d,d, c)) 会输出 d: 4.40 +5.500j c: 3.0000-5.0000j。想了解更多关于格式化的信息,可以查看 格式说明小语言的文档。

使用下面修改后的程序,在我的 Linux 系统上运行 ./mullermethod.py '(x-5)*(x-4)*(x+7)' 1 3 -10 0.000001(和你在提示中输入的参数一样)会打印出

The initial estimates to a root are:
f( 1.0 ) =  96.0
f( 3.0 ) =  20.0
f( -10.0 ) =  -630.0
 0: estimate to a root is f(  1.00000000000000) =  96.00000000000000
 1: estimate to a root is f( -4.10201287896889) = 213.71097514696675
 2: estimate to a root is f(  3.46320225345860) =   8.63161417086548
 3: estimate to a root is f(  3.90342357843416) =   1.15470992046251
 4: estimate to a root is f(  3.98002449809592) =   0.22371275706982
 5: estimate to a root is f(  3.99575149263503) =   0.04691400247817
 6: estimate to a root is f(  3.99909106270745) =   0.01000657113716
 7: estimate to a root is f(  3.99980529453210) =   0.00214213924168
 8: estimate to a root is f(  3.99995828046651) =   0.00045893227349
 9: estimate to a root is f(  3.99999106024078) =   0.00009833815063
10: estimate to a root is f(  3.99999808434378) =   0.00002107225517
11: estimate to a root is f(  3.99999958950253) =   0.00000451547380
12: estimate to a root is f(  3.99999991203627) =   0.00000096760109

然后程序就退出了。

#!/usr/bin/env python3.2
from math import *
from cmath import *

def evalFunction(f,x):
    return eval(f)

def main():
    from sys import argv
    f  = argv[1]           if len(argv)>1 else input("Input the function: ")
    p0 = float(argv[2])    if len(argv)>2 else eval(input("Input the first estimate to a root of the function: "))
    p1 = float(argv[3])    if len(argv)>3 else eval(input("Input the next  estimate to a root of the function: "))
    p2 = float(argv[4])    if len(argv)>4 else eval(input("Input the third estimate to a root of the function: "))
    toler = float(argv[5]) if len(argv)>5 else eval(input("Enter the tolerance: "))

    fp0 = evalFunction(f,p0)
    fp1 = evalFunction(f,p1)
    fp2 = evalFunction(f,p2)

    print("The initial estimates to a root are:")
    print("f(",p0,") = ",fp0)
    print("f(",p1,") = ",fp1)
    print("f(",p2,") = ",fp2)
    count = 0
    print ('{:2}: estimate to a root is f({:18.14f}) = {:18.14f}'.format(count,p0,fp0))
    fp3 = 1e9

    while count<30 and abs(fp3) >= toler:
        fp0 = evalFunction(f,p0)
        fp1 = evalFunction(f,p1)
        fp2 = evalFunction(f,p2)

        #Computes a,b,c 
        o = fp1-fp2
        n = fp0-fp2
        s = p1-p2
        r = p0-p2
        denom = r*s*(p0-p1)
        a = (s*n-r*o)/denom
        b = ((r**2)*o-(s**2)*n)/denom
        c = fp2
        count += 1

        #Compute roots
        x1 = (-2*c)/(b+(b**2-4*a*c)**.5)
        x2 = (-2*c)/(b-(b**2-4*a*c)**.5)

        if b>0:
            p3 = p2+x1
        else:
            p3 = p2+x2

        fp3=evalFunction(f,p3)
        print ('{:2}: estimate to a root is f({:18.14f}) = {:18.14f}'.format(count,p3,fp3))
        p2 = p3        

main()

注意,我没有看到 p0p1 在循环中发生变化(所以 fp0fp1 也没有变化)。根据我从 维基百科 的印象,你应该在说 p2 = p3 的地方做类似 p0, p1, p2 = p1, p2, p3 的操作。此外,为了减少函数的计算次数,如果你把 p0, p1, p2 = p1, p2, p3 改成 p0, p1, p2, fp0, fp1, fp2 = p1, p2, p3, fp1, fp2, fp3,就可以删除循环中的 fp0fp1fp2 的计算。

p0, p1, p2 = p1, p2, p3 替代 p2 = p3 后,可以在更少的迭代次数中找到更接近的结果(针对不同的根):

tini ~/sp/math > ./mullermethod.py '(x-5)*(x-4)*(x+7)' 1 3 -10 0.000001
The initial estimates to a root are:
f( 1.0 ) =  96.0
f( 3.0 ) =  20.0
f( -10.0 ) =  -630.0
 0: estimate to a root is f(  1.00000000000000) =  96.00000000000000
 1: estimate to a root is f( -4.10201287896889) = 213.71097514696675
 2: estimate to a root is f( -6.34710329529507) =  76.65637351948691
 3: estimate to a root is f( -6.95941163108092) =   5.31984100233008
 4: estimate to a root is f( -7.00059085626200) =  -0.07800105634618
 5: estimate to a root is f( -6.99999988135762) =   0.00001566079365
 6: estimate to a root is f( -6.99999999999998) =   0.00000000000281

撰写回答