gpt4 book ai didi

Python:迭代函数

转载 作者:太空宇宙 更新时间:2023-11-04 08:18:08 25 4
gpt4 key购买 nike

我正在尝试编写一个程序,以 xn+1 = xn2 + c 的形式为我迭代。我该怎么做?

例如,对于 c = 1 和 x0 = 1/2

(1/2)2 + 1 = 5/4,
(5/4)2 + 1 = 25/16 + 1 = 41/16
……等

我的代码在这里不起作用:

def main():
import math
print("This program iterates a function of the form x^2 + c:")
x=complex(input("Enter a seed value:"))
c=complex(input("Enter a value for c"))

for i in range(50):
f(0) = x*x + c
f(i) = f(i-1)*f(i-1) + c
print(f(i))
main()

Python 不允许我像 matlab 一样使用 f(0)f(i),有什么替代方案?

最佳答案

Tabbing 在 python 中很重要,请尝试下面的代码。很难猜测您的意图是什么,但它使您更接近最终结果

def main(x):
import math
print("This program iterates a function of the form x^2 + c:")
c = complex(input("Enter a value for c"))

print "C : %s" % c

f = [x * x + c]

for i in range(1, 50):
f.append(f[i - 1] * f[i - 1] + c)

print f

main(2)

关于Python:迭代函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10459403/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com