You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
toratoratora/方程求根上课学生代码.py

119 lines
2.4 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

# -*- coding: utf-8 -*-
"""
Created on Sun Dec 26 16:44:41 2021
@author: hzh
"""
# 求方程 f(x) = x3-5x2+10x-80 = 0的根二分法
# 绘图
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(-20, 20, 200)
y = x ** 3 - 5 * x ** 2 + 10 * x - 80
# 设置横轴纵轴刻度范围
plt.axis([-20, 20, -500, 500])
plt.grid('on') # 绘制网格
plt.plot(x, y)
plt.show()
# 二分法实现
E = 1e-10
x1, x2 = 0, 10
fx = 1
while abs(fx) > E:
x = (x1 + x2) / 2
fx = x ** 3 - 5 * x ** 2 + 10 * x - 80
if fx >= 0:
x2 = x
else:
x1 = x
print('x=', x, 'fx=', fx)
# 例2求x2-2=0的根即求2的平方根
def f(x):
return x ** 2 - 2
left = 1;
right = 2;
# left=-2;right=-1;
n = 0 # n用来统计二分次数
err = 1e-6 # 误差
while True:
n += 1;
middle = (left + right) * 0.5
if abs(f(middle)) < err:
print('f(x)=%.8f x=%.8f n=%d' % (f(middle), middle, n))
break
if f(middle) * f(left) > 0:
left = middle # 中点变为左边界
# right=middle #中点变为右边界
else:
right = middle # 中点变为右边界
# left=middle #中点变为左边界
'''
求方程f(x)=x3-11.1x2+38.8x-41.77的在[0,10]内的根,
请先画图,再用二分法求根。
'''
# 2牛顿迭代法
def f(x):
return x ** 2 - 2
def df(x):
return x * 2
x = 4;
err = 1e-6;
n = 0;
while True:
if abs(f(x)) < err:
print('fx=%.8f x=%.8f n=%d' % (f(x), x, n))
break
x = x - f(x) / df(x) #
n += 1
'''习题 利用Newton迭代法求下列方程的根
-sin(x)ex+5=0 位于0~10之间的根
x3-11.1x2+38.8x-41.77=0 位于0~10之间的根
xex-1=0 位于0~10之间的根
'''
# 牛顿割线法求方程的根
x0 = 1;
x1 = 2;
err = 1e-6;
n = 0
def f(x):
return x ** 2 - 2
for x0, x1 in [(-1, -2), (1, 2)]:
while True:
if f(x1) - f(x0) == 0:
print('False')
break
x = x1 - f(x1) / (f(x1) - f(x0)) * (x1 - x0)
n += 1
if abs(f(x)) < err:
print('fx=%.8f x=%.8f n=%d' % (f(x), x, n))
break
x0 = x1
x1 = x
'''
习题 利用Newton割线法求下列方程的根
x3-3=0 位于0~10之间的根
x3-11.1x2+38.8x-41.77=0 位于0~10之间的根
xex-1=0 位于0~10之间的根
'''
################begin##################
##习题 利用Newton割线法求下列方程的根
##x**3-3=0 位于0~10之间的根