为什么没有显示结果但没有显示错误

问题描述

我已经写了一个代码来获取函数的根,但是它没有显示任何结果,也没有显示任何错误:

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
    

解决方法

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
,
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循环永远无效

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...