MecSimCalc
ExploreSearchCreateDocsCommunityBlogPricing
    Apps

    Starred
    Go to app
    App Docs

In this example, we demonstrate how to plot a function in a single variable xx input by the user. Sympy is first used to interpret the expression and then plots the function given the two bounds provided by the user.


The code returns errors if the expression could not be interpreted, or if the plot was not rendered.

The output page uses the built-in if function to return the plot and the equation when no errors are given. Otherwise, a message is displayed to the user depending on the error identifyed.


Below I provide the code used for the example and the output page:


Code:

import sympy as sp
import matplotlib.pyplot as plt
import numpy as np
import base64
import io


#This function is used to create an image from the plot created using matplotlib.plt
def plt_show(plt, width=500, dpi=100):
    # Converts matplotlib plt to data string
    # dpi (dots per inch) is the resolution of the image
    # width is width of image in pixels
    bytes = io.BytesIO()
    plt.savefig(bytes, format='png', dpi=dpi)  # Save as png image
    plt.close()
    bytes.seek(0)
    base64_string = "data:image/png;base64," + \
        base64.b64encode(bytes.getvalue()).decode("utf-8")
    return ""



def main(inputs):
    f=inputs['func']
    a=inputs['a']
    b=inputs['b']
    Err=False
    img=False
    Err2=False
    try:
        g=sp.sympify(f)
    except:
        Err=True
    #Here I use sympy plot which is has matplotlib as its backend.
    if not Err:
        x=sp.symbols('x')
        try:
            sp.plot(g,(x,a,b))
            img=plt_show(plt,500)
        except:
            Err2=True
    return {"plot":img, "equation":f,"Error":Err,"ErrorPlot":Err2,"a":a,"b":b}


Output:

{% if outputs.Error %}
Please Enter a valid expression in x
{% elif outputs.ErrorPlot %}
Function could not be plotted. Please enter a valid expression in variable x
{% else %}
The following figure provides the plot for the function f(x)={{outputs.equation}} between {{outputs.a}} and {{outputs.b}}
{{outputs.plot|safe}}
{% endif %}
Similar apps:
Education
Featured
Math

Copyright © MecSimCalc 2024
Terms | Privacy