【发布时间】:2014-01-30 10:42:02
【问题描述】:
我完全是一个编程初学者,因此请告诉我我的问题的答案是否非常明显。
我一周前开始学习 python,并且在学习了使用 Newton-Raphson method 求解方程的基础知识后,我想出了一段代码,可以为您提供至少(仅)一个三次方程的解。这是我设计的代码:-
def deg3(a,b,c,d,g):
y=a*g**3+b*g**2+c*g+d
return y
def solvedeg3equation():
e=float(input("e= ")) #for ax^3+bx^2+cx+d=0, with maximum error of e
a=float(input("a= "))
b=float(input("b= "))
c=float(input("c= "))
d=float(input("d= "))
count=1
g=0.01
while abs(deg3(a,b,c,d,g))>e and count<=100:
count=count+1
if 3*a*g**2+2*b*g+c==0:
g=g+0.001
g=g-deg3(a,b,c,d,g)/(3*a*g**2+2*b*g+c)
if count<=100:
print("The best guess is:",g)
print("iterations required: ",count)
else:
print("maximum iterations exceeded ")
print("iterations: ",count,"current guess: ",g)
牛顿法的缺点之一是 or f'(x)=0,它会给出数学错误并崩溃。为了克服这个问题,我使用 g=g+0.001,如果 g 的当前值给出零导数,其中 g 是当前猜测。 有没有更好的方法来消除这个问题,而不使用复杂的函数?
我的另一个问题是,我是否可以包括提供多个根并对代码进行微小更改? 一个想法是改变猜测,使现在连续迭代带来关于另一个根。但我不知道如何做出这样的猜测,给出一个解决方案。
【问题讨论】:
-
这真是三个问题!要查看工作代码,请使用codereview.stackexchange.com
-
@jonrsharpe 我会减少问题的数量。 :)
标签: python equations newtons-method