想到用二分法求解函数方程的解,初学者,求指正:有什么需要改进的地方
def f1(x):
return pow(x,2) - 3*x + 2
# 函数的表达形式
def f(a,b,c):
# a和b为区间长度,c为精确度
while b - a != c:
if f1(a) * f1((a + b)/2)> 0:
a = (a + b)/2
elif f1(a) * f1((a + b)/2) < 0:
b = (a + b)/2
else:
print (a + b )/2
# 具体二分法求解过程
f(0,5,0)
求问:1)为什么一直输出是2,
2)如何修改得到另一个解 1
As a beginner, you must at least understand the basics of the language and basic operators first, except
/
是整除,所以两个整数相除时,要把其中一个变成小数(/2.0
).Are you sure
b - a != c
can be used as a loop condition and will not cause an infinite loop?