Пример #1
0
def main():
    # 一般項f(n)
    fn = sym.simplify("f(n)")
    # 左辺が0になるように漸化式を書く
    y = sym.simplify("f(n)-f(n-1)-f(n-2)")
    # 初期条件
    init = sym.simplify({"f(0)": 0, "f(1)": 1})
    # 初期条件iniの漸化式sをfについて解く
    fib_n = sym.rsolve(y, fn, init)
    print('Fibonacci sequenceの一般項の式は')
    print(fib_n)
    print('------------------------------')

    # -sqrt(5)*(1/2 - sqrt(5)/2)**n/5 + sqrt(5)*(1/2 + sqrt(5)/2)**n/5

    def fib_g(n):
        x = sym.symbols('x', nonnegative=True, integer=True)
        fib = -sym.sqrt(5) * (1 / 2 - sym.sqrt(5) / 2)**n / 5 + sym.sqrt(5) * (
            1 / 2 + sym.sqrt(5) / 2)**n / 5
        # Fibの式のxにnを代入
        formula = fib.subs(x, n)
        ans = int(sym.simplify(formula))
        print(formula, '=', ans)
        return ans

    print('0以上の整数を標準入力するとFibonacci sequenceの一般項の式と検算結果を出力する')
    n = int(input())
    print('検算結果')
    print('第',
          n,
          '項までの',
          'Fibonacci sequence', [fib_g(n) for n in range(0, n)],
          sep='')
Пример #2
0
def _selector(k, n):
    '''Compute the closed form for sequence defined by
f(0) = 1,
f(1) = ... = f(k-1) = 0,
f(n+k) = f(n)'''
    f = sp.Function('f')
    inits = {f(0): 1}
    inits.update({f(i): 0 for i in range(1, k)})
    return sp.rsolve(f(n + k) - f(n), f(n), inits)
Пример #3
0
    def apply(self, eqns, a, n, evaluation):
        'RSolve[eqns_, a_, n_]'

        # TODO: Do this with rules?
        if not eqns.has_form('List', None):
            eqns = Expression('List', eqns)

        if len(eqns.leaves) == 0:
            return

        for eqn in eqns.leaves:
            if eqn.get_head_name() != 'System`Equal':
                evaluation.message('RSolve', 'deqn', eqn)
                return

        if (n.is_atom() and not n.is_symbol()) or \
            n.get_head_name() in ('System`Plus', 'System`Times',
                                  'System`Power') or \
                'System`Constant' in n.get_attributes(evaluation.definitions):
            # TODO: Factor out this check for dsvar into a separate
            # function. DSolve uses this too.
            evaluation.message('RSolve', 'dsvar')
            return

        try:
            a.leaves
            function_form = None
            func = a
        except AttributeError:
            func = Expression(a, n)
            function_form = Expression('List', n)

        if func.is_atom() or len(func.leaves) != 1:
            evaluation.message('RSolve', 'dsfun', a)

        if n not in func.leaves:
            evaluation.message('DSolve', 'deqx')

        # Seperate relations from conditions
        conditions = {}

        def is_relation(eqn):
            left, right = eqn.leaves
            for l, r in [(left, right), (right, left)]:
                if (left.get_head_name() == func.get_head_name() and  # noqa
                        len(left.leaves) == 1 and isinstance(
                            l.leaves[0].to_python(), int) and r.is_numeric()):

                    r_sympy = r.to_sympy()
                    if r_sympy is None:
                        raise ValueError
                    conditions[l.leaves[0].to_python()] = r_sympy
                    return False
            return True

        # evaluate is_relation on all leaves to store conditions
        try:
            relations = [leaf for leaf in eqns.leaves if is_relation(leaf)]
        except ValueError:
            return
        relation = relations[0]

        left, right = relation.leaves
        relation = Expression('Plus', left,
                              Expression('Times', -1,
                                         right)).evaluate(evaluation)

        sym_eq = relation.to_sympy(
            converted_functions=set([func.get_head_name()]))
        if sym_eq is None:
            return
        sym_n = sympy.core.symbols(str(sympy_symbol_prefix + n.name))
        sym_func = sympy.Function(
            str(sympy_symbol_prefix + func.get_head_name()))(sym_n)

        sym_conds = {}
        for cond in conditions:
            sym_conds[sympy.Function(str(
                sympy_symbol_prefix + func.get_head_name()))(cond)] = \
                conditions[cond]

        try:
            # Sympy raises error when given empty conditions. Fixed in
            # upcomming sympy release.
            if sym_conds != {}:
                sym_result = sympy.rsolve(sym_eq, sym_func, sym_conds)
            else:
                sym_result = sympy.rsolve(sym_eq, sym_func)

            if not isinstance(sym_result, list):
                sym_result = [sym_result]
        except ValueError:
            return

        if function_form is None:
            return Expression(
                'List', *[
                    Expression('List', Expression('Rule', a, from_sympy(soln)))
                    for soln in sym_result
                ])
        else:
            return Expression(
                'List', *[
                    Expression(
                        'List',
                        Expression(
                            'Rule', a,
                            Expression('Function', function_form,
                                       from_sympy(soln))))
                    for soln in sym_result
                ])
Пример #4
0
    def apply(self, eqns, a, n, evaluation):
        'RSolve[eqns_, a_, n_]'

        # TODO: Do this with rules?
        if not eqns.has_form('List', None):
            eqns = Expression('List', eqns)

        if len(eqns.leaves) == 0:
            return

        for eqn in eqns.leaves:
            if eqn.get_head_name() != 'System`Equal':
                evaluation.message('RSolve', 'deqn', eqn)
                return

        if (n.is_atom() and not n.is_symbol()) or \
            n.get_head_name() in ('System`Plus', 'System`Times',
                                  'System`Power') or \
                'System`Constant' in n.get_attributes(evaluation.definitions):
            # TODO: Factor out this check for dsvar into a separate
            # function. DSolve uses this too.
            evaluation.message('RSolve', 'dsvar')
            return

        try:
            a.leaves
            function_form = None
            func = a
        except AttributeError:
            func = Expression(a, n)
            function_form = Expression('List', n)

        if func.is_atom() or len(func.leaves) != 1:
            evaluation.message('RSolve', 'dsfun', a)

        if n not in func.leaves:
            evaluation.message('DSolve', 'deqx')

        # Seperate relations from conditions
        conditions = {}

        def is_relation(eqn):
            left, right = eqn.leaves
            for l, r in [(left, right), (right, left)]:
                if (left.get_head_name() == func.get_head_name() and    # noqa
                    len(left.leaves) == 1 and
                    isinstance(l.leaves[0].to_python(), int) and
                    r.is_numeric()):

                    conditions[l.leaves[0].to_python()] = r.to_sympy()
                    return False
            return True
        relation = filter(is_relation, eqns.leaves)[0]

        left, right = relation.leaves
        relation = Expression('Plus', left, Expression(
            'Times', -1, right)).evaluate(evaluation)

        sym_eq = relation.to_sympy(
            converted_functions=set([func.get_head_name()]))
        sym_n = sympy.symbols(str(sympy_symbol_prefix + n.name))
        sym_func = sympy.Function(str(
            sympy_symbol_prefix + func.get_head_name()))(sym_n)

        sym_conds = {}
        for cond in conditions:
            sym_conds[sympy.Function(str(
                sympy_symbol_prefix + func.get_head_name()))(cond)] = \
                conditions[cond]

        try:
            # Sympy raises error when given empty conditions. Fixed in
            # upcomming sympy release.
            if sym_conds != {}:
                sym_result = sympy.rsolve(sym_eq, sym_func, sym_conds)
            else:
                sym_result = sympy.rsolve(sym_eq, sym_func)

            if not isinstance(sym_result, list):
                sym_result = [sym_result]
        except ValueError:
            return

        if function_form is None:
            return Expression('List', *[
                Expression('List', Expression('Rule', a, from_sympy(soln)))
                for soln in sym_result])
        else:
            return Expression('List', *[
                Expression('List', Expression(
                    'Rule', a, Expression('Function', function_form,
                    from_sympy(soln)))) for soln in sym_result])
Пример #5
0
#程序文件Pex13_2.py
import sympy as sp
sp.var('k')
sp.var('y', cls=sp.Function)
f = y(k + 1) - y(k) - 3 - 2 * k
f1 = sp.rsolve(f, y(k))
f2 = sp.simplify(f1)
print(f2)
Пример #6
0
#程序文件Pex13_1.py
from sympy import Function, rsolve
from sympy.abc import n
y = Function('y')
f = y(n + 2) - y(n + 1) - y(n)
ff = rsolve(f, y(n), {y(1): 1, y(2): 1})
print(ff)
Пример #7
0
# Program 13a: Computing bank interest.
# See Example 1.

from sympy import Function, rsolve
from sympy.abc import n

x = Function('x')
f = x(n + 1) - (1 + 3 / 100) * x(n)
sol = rsolve(f, x(n), {x(0): 10000})
print('x_n = {}'.format(sol))

x_5 = round(sol.subs(n, 5), 2)
print('x(5) = ${:,}'.format(x_5))
Пример #8
0
#程序文件ex3_1_3.py
import sympy as sp

sp.var('k')
y = sp.Function('y')
f = y(k + 2) - y(k + 1) - y(k)
s = sp.rsolve(f, y(k), {y(0): 1, y(1): 1})
print(s)
# Programs_13b: A second order recurrence relation.
# See Example 2.
from sympy import Function, rsolve
from sympy.abc import n
x = Function('x')
f = x(n + 2) - x(n + 1) - 6 * x(n)
sol = rsolve(f, x(n), {
    x(0): 1,
    x(1): 2
})
print('x_n=', sol)
Пример #10
0
#程序文件Pex13_2.py
import sympy as sp
sp.var('k'); sp.var('y',cls=sp.Function)
f = y(k+1)-y(k)-3-2*k
f1 = sp.rsolve(f, y(k)); f2 = sp.simplify(f1)
print(f2)
       
Пример #11
0
# #### The `glue:math` directive
#
# The `glue:math` directive is specific to LaTeX math outputs
# (glued variables that contain a `text/latex` MIME type),
# and works similarly to the [Sphinx math directive](https://www.sphinx-doc.org/en/1.8/usage/restructuredtext/directives.html#math).
# For example, with this code we glue an equation:

# In[13]:

import sympy as sym
f = sym.Function('f')
y = sym.Function('y')
n = sym.symbols(r'\alpha')
f = y(n) - 2 * y(n - 1 / sym.pi) - 5 * y(n - 2)
glue("sym_eq", sym.rsolve(f, y(n), [1, 4]))

# and now we can use the following code:
#
# ````md
# ```{glue:math} sym_eq
# :label: eq-sym
# ```
# ````
#
# to insert the equation here:
#
# ```{glue:math} sym_eq
# :label: eq-sym
# ```
#
Пример #12
0
# This file is aimed at being run as an interactive session via
# scitools file2interactive:
#
# Terminal> scitools file2interactive decay_analysis.py
#

import sys
import sympy as sym

p = sym.Symbol('p')
A_e = sym.exp(-p)

# Demo on Taylor polynomials
A_e.series(p, 0, 6)

"""
# NOTE: rsolve can solve recurrence relations:
a, dt, I, n = sym.symbols('a dt I n')
u = sym.Function('u')
f = u(n+1) - u(n) + dt*a*u(n+1)
sym.rsolve(f, u(n), {u(0): I})
# However, 0 is the answer!
# Experimentation shows that we cannot have symbols dt, a in the
# recurrence equation, just n or numbers.
# Even if we worked with scaled equations, dt is in there,
# rsolve cannot be applied.
"""

# Numerical amplification factor
theta = sym.Symbol('theta')
A = (1-(1-theta)*p)/(1+theta*p)