最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

python - Sympy rsolve function returns wrong results - Stack Overflow

programmeradmin1浏览0评论

I have the following recurrence relation:

an = 0.996 · an–1 + 0.004 · an–10 + 0.04

with initial conditions: an = 0 for all n ≤ 9.

Code:

import sympy as sp

n = sp.symbols('n')
y = sp.Function('y')
recurrence = sp.rsolve(
    y(n) - sp.Rational(0.996) * y(n-1) - sp.Rational(0.004) * y(n-10) - sp.Rational(0.04),
    y(n), 
    {
       y(0): 0,
       y(1): 0,
       y(2): 0,
       y(3): 0,
       y(4): 0,
       y(5): 0,
       y(6): 0,
       y(7): 0,
       y(8): 0,
       y(9): 0,
   }
)

The wrong result I get is just a constant number. Why do I not get an expression that depends on the variable n?

I have the following recurrence relation:

an = 0.996 · an–1 + 0.004 · an–10 + 0.04

with initial conditions: an = 0 for all n ≤ 9.

Code:

import sympy as sp

n = sp.symbols('n')
y = sp.Function('y')
recurrence = sp.rsolve(
    y(n) - sp.Rational(0.996) * y(n-1) - sp.Rational(0.004) * y(n-10) - sp.Rational(0.04),
    y(n), 
    {
       y(0): 0,
       y(1): 0,
       y(2): 0,
       y(3): 0,
       y(4): 0,
       y(5): 0,
       y(6): 0,
       y(7): 0,
       y(8): 0,
       y(9): 0,
   }
)

The wrong result I get is just a constant number. Why do I not get an expression that depends on the variable n?

Share edited Feb 10 at 15:38 Interpolated asked Feb 10 at 14:04 InterpolatedInterpolated 1155 bronze badges 2
  • This recurrence can be seen as a conditional expectation. At the beginning you have some initial number of trials, suppose 100. When we get the eagle we loose one trial and continue. When we get head we get 10$ but a gambler take from us 10 trials, so we continue with 90 games. So the question is: what is the expected money that we get after 100 games, E[Mony | Number of games = 100] = p*E[Money | NoG = 99 ] + p*( E[Money | NoG = 90 ] + 10) . As you can see in my example p = 0.996. – Interpolated Commented Feb 10 at 15:07
  • No, as you can see in the code above except 100 I have n. Im interested in the general formula for this recurrence. – Interpolated Commented Feb 10 at 15:23
Add a comment  | 

1 Answer 1

Reset to default 3

The recurrence first argument of rsolve is not an equality, it is the expression that the nth term is equal to, see docs.

So rsolve call should be

sp.rsolve(
  sp.Rational('0.996') * y(n-1) - sp.Rational('0.004') * y(n-10) - 
  sp.Rational('0.04'), 
  y(n), [0,]*10)

Seems like sympy cannot solve this recursion (note that you probably meant Rational('0.996') and not Rational(0.996)).

For getting a general element in this recurssion you can do the following:

from sympy import Function, symbols, Rational
from sympy.series.sequences import RecursiveSeq
y = Function('y')
n = symbols('n')
seq = RecursiveSeq(Rational('0.996')*y(n - 1) - Rational('0.004') * y(n-10) - Rational('0.04'), y(n), n, [0,]*10)
# y(30) =
seq.coeff(30)
发布评论

评论列表(0)

  1. 暂无评论