Last active
September 26, 2023 21:16
-
-
Save ncalm/20f379847374034f1a0d5d10abc14846 to your computer and use it in GitHub Desktop.
Use Python in Excel to integrate an expression and render the LaTeX expression and result to a plot
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| from sympy import integrate | |
| def integration_image(symbol: str, expr: str): | |
| """Integrates expr with respect to symbol | |
| integration_image(symbol='x', expr='exp(x)*sin(x) + exp(x)*cos(x)') | |
| Dependencies: 'from sympy import integrate' must be run before use | |
| """ | |
| # For example, put the text x in cell C2 | |
| x = Symbol(symbol) | |
| expr = sympify(expr) | |
| # integrate the expression | |
| integral_expr = integrate(expr, x) | |
| latex_expr = latex(expr) | |
| latex_integral_expr = latex(integral_expr) | |
| # return the expressions in a matplotlib plot | |
| fig, ax = plt.subplots(figsize=(5, 2)) | |
| suffix = latex(sympify('d' + symbol)) | |
| # Place the integral expression on one line | |
| ax.text(0, 0.6, f'$\\int {latex_expr} \\, {suffix}$', size=20, ha="left", va="center") | |
| # Place the equals sign and result on the next line | |
| # include the constant of integration in the result | |
| ax.text(0, 0.3, f'$= {latex_integral_expr} + C$', size=20, ha="left", va="center") | |
| ax.axis("off") | |
| return plt.show() | |
| integration_image("x",expr=xl("B3")) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| from sympy import integrate | |
| # For example, put the text x in cell C2 | |
| x = Symbol(xl("C2")) | |
| # convert the expression string to a symbolic expression | |
| # using the sympify method from the SymPy library | |
| # for example, put the expression exp(x)*sin(x) + exp(x)*cos(x) | |
| # in cell B3 | |
| expr = sympify(xl("B3")) | |
| # integrate the expression | |
| integral_expr = integrate(expr, x) | |
| latex_expr = latex(expr) | |
| latex_integral_expr = latex(integral_expr) | |
| # return the expressions in a matplotlib plot | |
| fig, ax = plt.subplots(figsize=(5, 2)) | |
| # Place the integral expression on one line | |
| ax.text(0, 0.6, f'$\\int {latex_expr} \\, dx$', size=20, ha="left", va="center") | |
| # Place the equals sign and result on the next line | |
| # include the constant of integration in the result | |
| ax.text(0, 0.3, f'$= {latex_integral_expr} + C$', size=20, ha="left", va="center") | |
| ax.axis("off") | |
| plt.show() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment