math

Given Y = 1/i calculate the next Y

I’m generating the following sequence , :
$$y_i = 1/i$$

where :

$$i = 1 \dots \infty$$
Given that I have the calculated-value at point x :

$$y_x$$

how should I calculate the next value $$y_{x+1}$$

I don’t know the index ‘x‘, I know only the calculated value.

For example, if $$y_x = 0.167$$ then $$y_{x+1} = 0.143$$ i.e. 1/6 implies 1/7

After a calculation I keep only the calculated value, not the current index.

Here is the formula :

$$ y_{x+n} = \frac {1} {{\frac 1 {y_{x}}}+n}$$


Detailed solution :

$$y_x = k; k= {\frac 1x}; x = {\frac 1k}$$

$$ y_{x+n} = \frac {1} {x+n} = \frac {1} {{\frac 1k}+n} = \frac {1} {{\frac 1 {y_{x}}}+n}$$

Incremental average

There are three ways to calculate an Average depending on the way we receive the data :

  1. Basic : we have all the data. In this case we just use the basic well known formula : $$Avg = \frac{1}{n} \sum_{i=0}^n x_i$$
  2. Moving average : calculated using rolling window
  3. Incremental average : the one that we will discuss now

The idea is to calculate the Basic average at every step w/o recalculating it from the whole sequence i.e. the data comes one value at a every time step.

Here is the formula :

$$a_n = a_{n-1} + \frac{x_n – a_{n-1}}{n}$$

here is how you can use it as a python closure function, so that you don’t have to carry the state :

def iavg():
  avg = 0
  n = 0
  def calc(value):
    nonlocal n,avg
    n += 1
    avg = avg + ((value - avg) / n)
    return avg
  return calc
  
avg = iavg()
print(f'2 => {avg(2)}')
print(f'4 => {avg(4)}')
print(f'6 => {avg(6)}')

-----

2 => 2.0
4 => 3.0
6 => 4.0

# (2+4+6) / 3 = 12/3 = 4