我已经写了一个代码来获取函数的根,但是它没有显示任何结果,也没有显示任何错误:
import math
from math import e
#finding root of f(x)=(e**-x)-x:
#f'(x)=(-e**-x)-1
#y=x-(f(x)/f'(x))
def f(x):
x=0
y=x-(((e**-x)-x)/((-e**-x)-1))
z=((y-x)/y)*100
while z<(10**-8):
print(f"The root is {y}")
x=y
答案 0 :(得分:0)
z
的初始值为100。
因此,它不会满足z < (10**-8)
并且不会进入while
循环。
但是,我们可以使用递归来找出所需的值:x = 0.5671432904
,而我们试图查找时需要设置一个最大迭代值,否则过程会出错。
此外,由于我们将使用递归,因此不再需要while循环,而是可以使用if语句进行检查。
这是我的解决方法:
from math import e
# desired output: x=0.5671432904
max_iter = 950
count = 0
result = -1
def f(x):
global count, result
count += 1
if count < max_iter:
y = x-(((e**-x)-x)/((-e**-x)-1))
z = ((y-x)/y)*100
if z < (10**8):
x = y
result = x
f(x)
f(0)
print("The root is {:.10f}".format(result))
输出:
The root is 0.5671432904
答案 1 :(得分:0)
from math import e
def f():
x = 0
y = x-(((e**-x)-x)/((-e**-x)-1))
z = ((y-x)/y)*100
print(z)
while z < (10**-8):
print("The root is {}".format(y))
x = y
f()
Z的输出为100
大于(10 **-8),因此while循环永远无效