Repeating sequence in Java / Python / Mathematica

How can you write the following instructions in these languages?

a(0) = 1
a_(n+1) = 1 - 1 / ( a_n + 3)

I need to find the smallest value nwhen a_n -> 0.732050....

My attempt at Mathematica

a[(x+1)_] = 1 - 1/(a[x_] + 3)

This is obviously the problem a[(x+1)_]. However, I do not know how to do this iteratively in Mathematica.

+3
source share
6 answers

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 gives off 8, suggesting that optimization, such as eliminating recursion or memoizing, is probably not justified.

, , , - ...:

# get a function 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

:

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

, limit HOF :

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

, : next_prev " ", limit " ".

, : itertools , ...; -):

import itertools

def next_prev(f):
  values = itertools.imap(f, itertools.count())
  prv, nxt = itertools.tee(values)
  nxt.next()
  return itertools.izip(prv, nxt)
+4

Mathematica

a[0] = 1;
a[n_] := a[n] = 1 - 1/(a[n-1] + 3)

( memoization.)

, [n] ( ) sqrt (3) -1:

Solve[x == 1 - 1/(x+3), x]
+8

Java

double A = 1;
int n = 0;
while (true) {
  System.out.println(n + " " + A);
  A = 1 - 1 / (A + 3);
  n++;
}

Python

A = 1.0
n = 0
while 1:
  print n, A
  A = 1 - 1 / (A + 3)
  n += 1
+3

Mathematica:

a[0] := 1
a[k_] := 1 - 1/(a[k - 1] + 3)

k = n + 1, . .

+3

Python

next = lambda x: 1.0 - (1.0 / (float(x) + 3.0))
last, z, count = -1, 0.0, 0
while last != z:
  print count, z
  last, z, count = z, next(z), count+1

"while True" , . , , . . ℵ-null.

+2

Mathematica, :

In[66]:= NestWhileList[1 - 1/(#1 + 3) &, 1, 
 RealExponent[Subtract[##]] > -8 &, 2]

Out[66]= {1, 3/4, 11/15, 41/56, 153/209, 571/780, 2131/2911, \
7953/10864, 29681/40545}

10 ^ -8. , 8 :

In[67]:= Length[%]

Out[67]= 9
+1

Source: https://habr.com/ru/post/1719666/


All Articles