How can I create sequence and math functions in python?

1

How can I make the interpreter 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 operation of the loop. Hard to understand but this is nothing less than a sequencing and mathematical series, but I wanted to apply it to python to solve mathematical problems.

    
asked by anonymous 23.12.2017 / 23:58

2 answers

0

There are two ways:

1) The easiest - is not to try to use math notation, and translate everything from mathematical notation to the language you're using, in this case Python . (If you're thinking, the notation we use for math is a type of programming language too)

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

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

That is, just as in the case of mathematical notation, the function uses the result of itself in an earlier iteration. The difference for math is that in math we tend to see "okay, I imagine the previous value is there and it is so much" - in programming language, the previous value has to be computable - so nor can you express this function without having an initial value. (Okay, actually it can, but if it was called it would fall into a case of infinite recursion and shut down the program.)

2) Use a subsystem that implements objects that behave like math symbols. In the case of Python, there is the SymPy project. It allows you to specify Python objects with behavior very close to math symbols (but still within the Python syntax - for example, the 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 numeric value by calling specific methods.

SymPy is a great project, done by professionals in mathematics and programming over the course of several years - it's practically another language on top of the Python language.

It is clear that you try to make a system that can interpret your mathematical expression using symbols and make the calculations from it is rather complex. It could be the design of a lifetime, in fact.

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

If you are going to work with mathematical formulas, and want to work algebraically with such equations, stop to study SymPy - install, do the tutorials, and understand it. Just so you can do things with it, because it combines two complex notation systems - Python and Math in a third.

And - unless it's a specific project for that, forget about the approach of trying to do the interpretation and calculation of symbolic expressions of math by yourself - this would reinvent Formula 1 car, and you'd have to start from wheel.

    
27.12.2017 / 13:21
1

It's not simple, there are different mathematical operations and types of equations, what you can do is split the string and evaluate everything in loop, such as for or while .

There is nothing native that does this, you can create by gradually 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)

Then as you pass c to each loop you can evaluate where numbers are, where 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 on repl.it

Libraries

There are some ready-made libs you can facilitate, such as link , 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 out the following link: link

p>     
24.12.2017 / 01:42