一、简介
对于区间[a,b]上连续不断且f(a)·f(b)<0的函数y=f(x),通过不断地把函数f(x)的零点所在的区间一分为二,使区间的两个端点逐步逼近零点,进而得到零点近似值的方法叫二分法。
二、代码示例
# !/usr/bin/env python
# coding=utf-8
import sys
import matplotlib.pyplot as plt
# 给定一个函数f(x)
import numpy as np
def function_1(x):
fun = x*x-1
return fun
# 判断其在区间[a,b]上是否有一个值为0的点
def dichotomy():
a = float(input("请输入数字a:"))
b = float(input("请输入数字b:"))
# 确定二分区间
if a < b:
print ("输入的区间为:")
print (a, b)
else:
print ("请重新输入a,b;b要大于a/n")
sys.exit()
# 判断在区间上是否存在0点
if function_1(a)*function_1(b) < 0:
print ("函数在该区间存在0值/n")
else:
print ("函数在该区间不存在0值或存在2个0值,请重新确定区间")
sys.exit()
# 进行二分运算
m = (a+b)/2
count = 0
while count < 1000:
m = (a+b)/2
if abs(function_1(m)) < 0.00001:
break
if function_1(a)*function_1(m) <= 0:
b = m
else:
a = m
count = count+1
print("当函数取0值时x的取值为:")
print (m)
print("循环的次数为:")
print (count)
x = np.linspace(-3, 3, 1000)
y = x * x - 1
plt.figure(figsize=(16, 10))
plt.plot(x,y,'red',linewidth=2)
plt.show()
dichotomy()
三、运行结果
请输入数字a:0
请输入数字b:3
输入的区间为:
0.0 3.0
函数在该区间存在0值/n
当函数取0值时x的取值为:
0.9999961853027344
循环的次数为:
17