如何在python中使输出成为输入

2024-04-24 17:33:07 发布

您现在位置:Python中文网/ 问答频道 /正文

>>> import math

#defining first function
>>> def f(a):
        return a-math.sin(a)-math.pi/2

#defining second fuction
>>> def df(a):
        return 1-math.cos(a)

#defining third function which uses above functions
>>> def alpha(a):
        return a-f(a)/df(a)

如何编写一个代码,其中alpha(a)取a=2的起始值,alpha(2)的解将成为下一次的输入。例如:假设alpha(2)是2.39,因此下一个值是alpha(2.39),并且继续{50次迭代}。谁能帮我一点忙吗。提前谢谢。你知道吗


Tags: importalphadfreturndefpifunctionmath
2条回答

你可以把它具体化。你知道吗

import math

class inout:
    def __init__(self, start):
        self.value = start
    def f(self, a):
        return a-math.sin(a)-math.pi/2
    def df(self, a):
        return 1-math.cos(a)
    def alpha(self):
        self.value = self.value-self.f(self.value)/self.df(self.value)
        return self.value

然后创建一个inout对象,每次调用它的alpha方法时,它都会给出序列中的下一个值。你知道吗

demo = inout(2)
print(demo.alpha())

您可以让程序使用for循环进行迭代,并使用变量存储中间结果:

temp = 2                # set temp to the initial value
for _ in range(50):     # a for loop that will iterate 50 times
    temp = alpha(temp)  # call alpha with the result in temp
                        # and store the result back in temp
    print(temp)         # print the result (optional)

print(temp)将打印中间结果。它不是必需的。它只演示如何在整个过程中更新temp变量。你知道吗

相关问题 更多 >