版权声明:博主的博客不值钱随便转载但要注明出处 https://blog.csdn.net/easylovecsdn/article/details/84312353
前言
之前我们讨论了划界法求取方程根(二分、试位),本次我们来讨论开放法求取方程根(迭代法、牛顿切线法、弦截法),本次代码熬夜赶工,有不足之处希望给我指正,本篇内容今后还会修改,图像和流程图会在以后补上。
补充
下面的所有判0,严格意义上不应该是完全的0,应该改为1e-10或-1e-10,因为可能存在精度误差,如果不判,那就把maxn的计数范围跑完。
代码
1.迭代
# -*- coding: utf-8 -*-
import math
maxn = 99999
def f(x) :
return x**3 - x - 1.0
def g(x) :
return pow(x + 1, 1/3)
def g_(x) :
return 1/3 * pow(x + 1, -(2/3))
x = 1.5
if (math.fabs(g_(x)) < 1.0) :
for i in range(maxn) :
x = g(x)
if (f(x) == 0) :
break
print("f(%.6lf) = %.3lf" %(x, f(x)))
else :
print("Can not output solution\n")
2.牛顿切线
# -*- coding: utf-8 -*-
import math
maxn = 9999
def f(x) :
return math.exp(x) - 3
def f_(x) :
return math.exp(x)
x = -2
for i in range(maxn) :
temp = f(x)
if (temp > 0 and temp <= 1e-10) or (temp < 0 and temp >= -1e-10) :
break
x = x - f(x) / f_(x)
print("f(%.5lf) = %.3lf\n" %(x, f(x) ) )
3.弦截
# -*- coding: utf-8 -*-
import math
maxn = 9999
def f(x) :
return x**3 - 0.2 * x**2 - 1.2
def Y(x, a, b) :
temp = f(b)
return ((temp - f(a)) / (b - a)) * (x - b) + temp
def f_(x) :
return 3 * x**2 - 0.4 * x
a = 1.0
b = 1.5
mid = (a + b) / 2
if (f_(a) > 0 and Y(mid, a, b) > f(mid)) or (f_(a) < 0 and Y(mid, a, b) < f(mid)) :
for i in range(maxn) :
temp = f(a)
if (math.fabs(temp) <= 1e-5) :
break
a = a - (a - b) * temp / (temp - f(b))
ans = a
else :
for i in range(maxn) :
temp = f(b)
if (math.fabs(temp) <= 1e-5) :
break
b = b - (b - a) * temp / (temp - f(a))
ans = b
print("f(%.5lf) = %.3lf\n" %(ans, math.fabs(f(ans)) ) )