Repetitive sequences in Java / Python / Mathematica
How to write the following statements in a given language?
a(0) = 1 a_(n+1) = 1 - 1 / ( a_n + 3)
When a_ When n – >, I need to find the minimum value of n 0.732050 ….
My attempt at Mathematica
a[(x+1)_] = 1 - 1/(a[x_] + 3)
The problem is obviously [(x 1)] However, I don't know how to do it iteratively in Mathematica
Solution
Python, simplest:
def a(n): if n == 0: return 1 return 1 - 1 / float(a(n-1) + 3) # limit is sqrt(3) - 1 limit = 3.0 ** 0.5 - 1.0 # get 9 digits' precision i = 0 while abs(a(i) - limit) > 1.0e-9: i += 1 print i
This sends an 8, indicating that optimization such as recursive elimination or memory may not be guaranteed
Of course, usually we want to get limitations numerically rather than analytically, so the normal way of loops will be different - and it's best to encapsulate them in higher-order functions...:
# get a function's limit numerically def limit(f,eps=1.0e-11): prevIoUs_value = f(0) next_value = f(1) i = 2 while abs(next_value - prevIoUs_value) > eps: prevIoUs_value = next_value next_value = f(i) i += 1 return next_value
Nontrivial loop logic is usually best encapsulated in generators:
def next_prev(f): prevIoUs_value = f(0) i = 1 while True: next_value = f(i) yield next_value,prevIoUs_value i += 1 prevIoUs_value = next_value
With the help of this generator, the limit Hof becomes simpler:
def limit(f,eps=1.0e-11): for next_value,prevIoUs_value in next_prev(f): if abs(next_value - prevIoUs_value) < eps: return next_value
Notice how useful separation is: next_ Prev embodies the concept of "get the next and previous value of the function", which is limited to "when the loop ends"
Last but not least, itertools usually provides a good generator alternative that allows you to encapsulate picky iterative logic in a fast way (although it does require some habits...; -):
import itertools def next_prev(f): values = itertools.imap(f,itertools.count()) prv,nxt = itertools.tee(values) nxt.next() return itertools.izip(prv,nxt)