python求方程近似解_Python – 实现数值方程求解器(Newton-Raphson)

我警告你,这可能会令人困惑,我写的代码更多的是思维导图而不是完成代码.

我正在尝试使用Newton-Raphson方法来求解方程.

我无法弄清楚的是如何写这个

Python中的等式,用于计算最后一次近似(xn)的下一个近似值(xn 1).我必须使用循环,越来越接近真实的答案,并且当近似值之间的变化小于变量h时,循环应该终止.

>我如何编写等式的代码?

>当近似值不再变化时,如何终止循环?

计算方程f的导数,在点x,精度为h(这用于求解方程式())

def derivative(f, x, h):

deriv = (1.0/(2*h))*(f(x+h)-f(x-h))

return deriv

数值方程求解器

假设循环直到近似值之间的差异小于h

def solve(f, x0, h):

xn = x0

prev = 0

while ( approx - prev > h):

xn = xn - (f(xn))/derivative(f, xn, h)

return xn

解决方法:

以下是N-R求解器的实现,扩展了您上面所写的内容(完整,有效).我添加了一些额外的行来显示正在发生的事情……

def derivative(f, x, h):

return (f(x+h) - f(x-h)) / (2.0*h) # might want to return a small non-zero if ==0

def quadratic(x):

return 2*x*x-5*x+1 # just a function to show it works

def solve(f, x0, h):

lastX = x0

nextX = lastX + 10* h # "different than lastX so loop starts OK

while (abs(lastX - nextX) > h): # this is how you terminate the loop - note use of abs()

newY = f(nextX) # just for debug... see what happens

print "f(", nextX, ") = ", newY # print out progress... again just debug

lastX = nextX

nextX = lastX - newY / derivative(f, lastX, h) # update estimate using N-R

return nextX

xFound = solve(quadratic, 5, 0.01) # call the solver

print "solution: x = ", xFound # print the result

输出:

f( 5.1 ) = 27.52

f( 3.31298701299 ) = 6.38683083151

f( 2.53900845771 ) = 1.19808560807

f( 2.30664271935 ) = 0.107987672721

f( 2.28109300639 ) = 0.00130557566462

solution: x = 2.28077645501

编辑 – 你也可以检查newY的值并在它“足够接近零”时停止 – 但通常你会继续这样做,直到x的变化为< = h(你可以争论=符号的值)一个数值方法 - 我更倾向于更加强调

标签:python,while-loop,numerical-methods

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值