Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

From string to sympy expression

Recently I was working on a web application, using Flask and sympy libraries. The user enters his equation in a textarea and Flask rechieve it as a string. I would like to have the possibility to calculate the result of this equation,by using sympy function solve(). But for this I must convert this string to an sympy expression. How could I do that?

`

from flask import Flask,request,render_template,flash
from sympy import *
from sympy.parsing.sympy_parser import *

x = symbols('x')
app = Flask(__name__)
app.secret_key = 'mysecretkey'


def calculate_():
    first_eq = request.form['first_eq']

    first_eq2= parse_expr(first_eq)
    result = solve(first_eq2)
    return result


@app.route("/",methods=['GET', 'POST'])
def myGet():

    return render_template("my-form.html")

@app.route("/myPost/",methods=['GET', 'POST'])
def myPost():
    answer = request.form['answer']
    result_of_answer=solve(Eq(answer),x)
    result = calculate_()
    try:
        if result == result_of_answer:
            flash("you got it!")
        else:
            flash("no, it's wrong")
            return render_template("my-form.html")
    except:
        flash("sorry, wrong type. Try again!")
        return render_template("my-form.html")
if __name__ == '__main__':
    app.run()`
like image 780
Vasile Avatar asked Nov 09 '15 10:11

Vasile


People also ask

How do you evaluate expressions in SymPy?

To evaluate a numerical expression into a floating point number, use evalf . SymPy can evaluate floating point expressions to arbitrary precision. By default, 15 digits of precision are used, but you can pass any number as the argument to evalf .

How can I substitute SymPy?

The subs() function in SymPy replaces all occurrences of first parameter with second. This function is useful if we want to evaluate a certain expression. For example, we want to calculate values of following expression by substituting a with 5.

How do you approximate in SymPy?

Basics. Exact SymPy expressions can be converted to floating-point approximations (decimal numbers) using either the . evalf() method or the N() function.


1 Answers

The function you're looking for is sympify. http://docs.sympy.org/latest/modules/core.html#sympy.core.sympify.sympify

like image 125
asmeurer Avatar answered Sep 30 '22 03:09

asmeurer