How can I create sequence and math series functions in python?

Asked

Viewed 630 times

1

How can I get the interpreter to understand what the previous value of a mathematical function is, for example: "Xn = 3.7(Xn-1)" where "n-1" means the result of the previous loop operation. Kind of hard to understand but this is nothing short of a sequence and mathematical series, but I wanted to apply it to python to solve mathematical problems.

  • Read about recursion.

  • OK, thank you very much!

2 answers

1

It’s nothing simple, there are different mathematical operations and types of equations, what you can do is split the string and evaluate everything in a loop, like for or while.

There is nothing native that does this, you can slowly create by analyzing one by one of the characters in something like:

equacao = "Xn = 3,7(xn-1)";

for c in equacao:
    c = c.strip() # Elimina espaços

    if c: # Checa se é vazio
        print(c)

So as you go through c with each loop you can evaluate where the numbers are, where the parentheses begin and end, simple example with + and - only (tested in Python 3):

# -*- coding: utf-8 -*-

class Exemplo:
    ultimaoperacao = '+';
    ultimovalor = '';
    total = 0;

    def calcularPendente(self):
        if self.ultimovalor == '':
            return None

        valor = int(self.ultimovalor)

        self.ultimovalor = ''

        if self.ultimaoperacao == '+':
           self.total += valor
        elif self.ultimaoperacao == '-':
           self.total -= valor


    def __init__(self, equacao):
        for c in equacao:
            c = c.strip() # Elimina espaços

            if c == '': # Se for vazio i loop irá para o próximo
                continue
            elif c.isnumeric():
                self.ultimovalor += c
                continue

            # calcula os pendentes quando mudar o operador
            self.calcularPendente()

            if c == '+':
                self.ultimaoperacao = '+';
            elif c == '-':
                self.ultimaoperacao = '-';

            self.ultimovalor = '';

        # Após o loop calcula o pendente
        self.calcularPendente()


    def resultado(self):
        return self.total

print( Exemplo("1 + 2").resultado() )
print( Exemplo("10 - 5").resultado() )
print( Exemplo("1 + 1 + 2").resultado() )
print( Exemplo("1 + 2 + 3 + 4 + 5 - 6 - 2").resultado() )

Example in repl it.


Libraries

There are some ready libs that can facilitate, such as https://pypi.python.org/pypi/cexprtk, it can be installed via pip:

pip install cexprtk

An example of simple use:

from cexprtk import evaluate_expression

print( evaluate_expression("(5+5) * 23", {}) ) # resultado 230.0

Other libs you can check the following link: https://pypi.python.org/pypi?%3Aaction=search&term=Mathematical&submit=search

  • If I were to say, I would say that what AP needs is simple recursiveness and not analysis of the mathematical expression in a string. I could be wrong, but this would be a duplicate of any one that addresses recursion.

  • exact, Anderson. An example would be to reproduce the sequence of fibbonacci Numbers: def Fibonacci(n): ... a, b = 0, 1 ... while b < n: .. print b, .. a, b = b, a+b ... Fibonacci(100) #1 2 3 8 13 21 34 55 89

0


Are two forms:

1) the easiest - is not trying to use mathematical notation, and translate everything from mathematical notation to the language you are using, in this case Python (If you think about it, the notation we use for mathematics is a kind of programming language too)

In that case, equacao = "Xn = 3,7(xn-1)"; tries to denote a function that depends on the output of the previous series. These cases, we can solve in structured programming with the use of recursive functions - but it is always necessary a stop code that you did not give. Assuming the criterion is "X1 = 1", the above expression can be written as the Python function:

def X(n):
   if n == 1:
       return 1
   return 3.7 * X(n - 1)

That is, exactly as in the case of mathematical notation, the function uses the result of itself in an earlier iteration. The difference for mathematics is that in mathematics we tend to see "okay, I imagine the previous value is there and it’s so much" - in programming language, the previous value has that being computable - so you can’t even express this function without having an initial value. (Okay, actually it can, but if it were called it would fall into an infinite recursion case and end the program).

2) Use a subsystem that implements objects that behave like mathematical symbols. In the case of Python, there is the project Sympy. It allows you to specify objects in Python with behavior very close to that of mathematical symbols (but, still within Python syntax - for example, multiplication will require the operator "*" ). With Sympy it is possible to create Python objects equivalent to equations like the one you present, and it can make algebraic use of it, and calculate a numerical value by calling specific methods.

Sympy is a big project, done by programming and math professionals over several years - it’s practically another language on top of the Python language.

Hence it is clear that you try to make a system that can itself interpret its mathematical expression that makes use of symbols and make the calculations from it is something quite a lot complex. It may be the project of a life, in fact.

In short: if you have few equations of this type, and you need a way of calculating the numerical results of it using a computer, translate one by one to the Python "notation".

If you are going to work with mathematical formulas, and want to be able to work algebraically with equations of this type, stop to study Sympy - install, do the tutorials and understand it. Only then will you be able to do things with it, because ee combines two complex notation systems - Python and Mathematics in a third.

And - unless it’s a specific project for that, forget the approach of trying to do the interpretation and calculation of symbolic expressions of mathematics for yourself - that would be reinventing the formula 1 car, and you would have to start from the wheel.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.