对于只涉及基本 python 编程的类,我无法让 Muller 算法的这段代码正常工作。我的程序还没有像输出那样包含任何虚数,而且我的停止标准也不能正常工作,但现在我最关心的是让下面的输出中的数字正确打印。我将输出作为代码发布,因为我是这个网站的新手,它一直给我一个错误,说我的“代码格式不正确”
很感谢任何形式的帮助!
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()