帮助编写代码。我做错什么了?你知道吗
我的目标是通过精确的迭代方法找到方程的根:ξ = 10^-5f(x)
(或ε = 0.00001
)。
方程:2.056x^43+3x^31+4x^12+x^8-3,478 = 0
。你知道吗
代码:
# -*- coding: utf-8 -*-
import math
#Definition of function
def phi (x):
return 2.056*(x**43)+3*(x**31)+4*(x**12)+(x**8)-3.478
#Recursive search function
def findRoot (f, x, q, epsilon):
fx=f(x)
#Checking the ending condition
if (1 / (1-q) * abs (fx-x) <epsilon):
print 'Root value', fx
print '1 / (1-q) * abs (fx-x)=', 1 / (1-q) * abs (fx-x)
else:
print 'Current approximation', fx
print '1 / (1-q) * abs (fx-x)=', 1 / (1-q) * abs(fx-x)
findRoot (f, fx, q, epsilon)
findRoot(phi, 0.5, 0.5, 0.00001)
执行
Current approximation -3.4731171861
1 / (1-q) * abs (fx-x)= 7.94623437221
Current approximation -3.66403074312e+23
1 / (1-q) * abs (fx-x)= 7.32806148624e+23
Traceback (most recent call last):
File "Zavd1f.py", line 17, in <module>
findRoot(phi, 0.5, 0.5, 0.00001)
File "Zavd1f.py", line 16, in findRoot
findRoot (f, fx, q, epsilon)
File "Zavd1f.py", line 16, in findRoot
findRoot (f, fx, q, epsilon)
File "Zavd1f.py", line 8, in findRoot
fx=f(x)
File "Zavd1f.py", line 5, in phi
return 2.056*(x**43)+3*(x**31)+4*(x**12)+(x**8)-3.478
OverflowError: (34, 'Numerical result out of range')
这种迭代方法只是将函数值作为参数重复应用。只有当你的初始猜测在收敛半径内时,这才有效。你的不是。您需要实现一个算法,使在每次迭代中更接近。你知道吗
当前算法的初始猜测值为0.5;这提高到高次幂(8足够高)接近0,因此我们得到的结果非常接近常数项。你知道吗
所以。。。它要么是你的起始值,要么是你的算法,要么是你的算法实现。你知道吗
我玩了一下你的代码;我认为你可能在尝试实现一个二分算法(从q=0.5)或牛顿法。无论哪种情况,你都忽略了编码下一个猜测。你知道吗
您只需使用f(x)作为根的下一个猜测,即
x
值。这是不正确的;您需要记住这是一个y
值;您可以使用它来计算下一个x
值。f(x)
本身并不是下一个猜测。你知道吗因为你没有发布你的算法,我不确定两倍的错误(你硬编码三次的表达式)应该与迭代过程有关。你知道吗
相关问题 更多 >
编程相关推荐