我写了一段python代码,使用二分法找到2*x-4的根。
def func(x):
return 2*x-4
def bisection(a,b):
if (func(a) * func(b) >= 0):
print("You have not assumed right a and b\n")
return
c = a
while ((b-a) >= 0.01):
c = (a+b)/2
if (func(c) == 0.0):
break
if (func(c)*func(a) < 0):
b = c
else:
a = c
print("The value of root is : ","%.0f"%c)
a =-2
b = 4
bisection(a, b)现在我希望函数输入应该由用户以mx+n的形式给出,其中m和n是整数。有人能帮上忙吗?我怎么做?
发布于 2021-12-05 06:09:17
m, n = list(map(int, input("Please enter the value of m, n for f(x) = mx +n").split()))
def Input():
a, b = list(map(int, input("Enter values of a, b: ").split()))
if f(a)*f(b)<0:
Bisection(a, b)
else:
print("Oops! The root of function doesn't belong to the above domain\nPlease try to again:")
Input()
def f(x):
return m*x + n
def Bisection(a, b):
c = (a+b)/2
if f(c)*f(b)<0:
Bisection(c, b)
elif f(c)*f(a)<0:
Bisection(c, a)
elif f(c)==0:
print(c)
Input()我们知道二分法,牛顿-拉夫森方法,或者大多数数值方法都是迭代过程,所以我们最好在函数内部使用函数:当然是f(f(f(f.....)!通过检查条件。
这里我用了elif f(c)==0,这是我们不能用于二次/三次或高阶多项式的东西,因为不是所有类型的方程都能得到精确的根,比如f(x) = mx^2 - n,m, n > 0,但是,我们可以定义要执行的迭代。通过询问like,请输入要执行的迭代次数:
https://stackoverflow.com/questions/70225820
复制相似问题