Skip to content
DeepForgeby svx
All problems
MediumCalculusca-175

Difference Equation Solve

Problem

Solve the first-order linear recurrence y[n] = a*y[n-1] + b with y[0] = y0 in closed form.

For a != 1 the solution is y[n] = a^n * y0 + b * (1 - a^n) / (1 - a); for a = 1 it is y[n] = y0 + n*b. Given a, b, y0, and n >= 0, return y[n].

Hint

The fixed point b/(1-a) plus a transient a^n controls the solution.

Test cases

case 1
in: [0.5,1,0,3]
expected: 1.75
case 2
in: [1,2,5,4]
expected: 13
case 3
in: [2,0,3,5]
expected: 96
case 4
in: [0.5,2,1,10]
expected: 3.9970703125
Starter codePython
def difference_equation(a, b, y0, n):
    # Your code here
    pass

4 test cases · run your code against them in the editor