第二篇随笔

9102年11月底,工科男曹**要算一个方程f(x)=0的根,其中f(x)表达式为:

因为实数范围内f(x)=0的根太多,所以本文只研究-2<x<2的情况.这个式子长的太丑了,曹**看着觉得不爽,导之,得一f'(x)

这个式子更丑,但是,我们有牛顿迭代法,可以构造迭代序列{xn}满足:

其中f'(xn)不等于0.可以证明,只要初值选的好,序列可以收敛到要求的根.然后就可以写程序求根了.

先上函数图像(由desmos绘制),看到指定区间上有5个零点.然后,零点附近取值吧.

再上效果

 

结果还是不错的.

最后,上代码.f(x)和f'(x)用委托的方式传入calc函数.委托注意实例化

public delegate function myfunc(x as double) as double
public function func0(x as double) as double
    return exp(x) + pow(x, 4) * sin(pow(x, 3))
end function
public function func0derive(x as double) as double
    return exp(x) + 4 * pow(x, 3) * sin(pow(x, 3)) + 3 * pow(x, 6) * cos(pow(x, 3))
end function
dim f0 as new myfunc(addressof func0)
dim fd0 as new myfunc(addressof func0derive)

 

calc的参数中f和fd分别是指向f(x)和f'(x)的函数指针,x0为初值,eps为精度,cnt为迭代次数

用传引用的方式,通过sol返回计算结果.

返回true为没有出错,false为出错.

 1 public function calc(f as myfunc, fd as myfunc, x0 as double, eps as double, cnt as integer, byref sol as double) as boolean
 2         if cnt <= 0 or f is nothing or fd is nothing then
 3             return false
 4         end if
 5         try
 6             sol = 0
 7             dim x as double = x0, c0 as integer = 0
 8             while math.abs(x) > eps and cnt > c0
 9                 x = x - f(x) / fd(x)
10                 c0 += 1
11             end while
12             sol = x
13             return true
14         catch ex as exception
15             return false
16         end try
17     end function