美文网首页
2018-10-15

2018-10-15

作者: 木马音响积木 | 来源:发表于2018-10-15 22:35 被阅读0次

f(x)= x^3 + 4 x^2 -8

f'(x)=3x^2 +8x

今天一个朋友,vb 编程遇到个小问题,
我写了个python 程序,,仅供参考。

牛顿割线法,如图


牛顿割线法.jpg

我们现在91maths 上,看看函数的图像,找到初值,如1.24,

确定一个初始值.jpg

注意,我们是从右侧向左侧逼近,也就是x 不断变小 方向。
二阶导数 f''(x)=6x+8 > 0 在[0,2] 都是凹函数,保障了,我们从1.24开始收敛是对的。

import math  

def f(x):
    #  f(x) = x^3 + 4 x^2 -8
    kk= math.pow(x, 3) + 4 * ( math.pow(x, 2) ) - 8
    #kk= x*x*x + 4 * ( x*x ) - 8   # --easy way
    return kk
    
def fl(x):
    #  f'(x)=3x^2 + 8 x
    hh = 3 * ( math.pow(x, 2) ) + 8 * x
    return hh
    
def nn(x0):
    i = 1
    while i < 99:  # create the limit , the max loop 
        x = x0 - (f(x0) / fl(x0))
        # if it is difficult for you , look at this
        #x = x0 - (  (x0*x0*x0 + 4 * ( x0*x0 ) - 8 )    / ( 3*x0*x0+8*x0  )        )   
        if abs(f(x0) / fl(x0)) < 0.0001:   #get from the topic ,this is a const
            #return (x,i)
            return x
        x0 = x
        i = i + 1
        
jj = 1.24   # the first guess ,use 91maths website,from right to left
print(nn(jj))  

# 1.2360679775356798 -- 结果

在 91maths 验证的解的情况,,如下图


宫1111.jpg

相关文章

网友评论

      本文标题:2018-10-15

      本文链接:https://www.haomeiwen.com/subject/rpnqzftx.html