Plotting an equation with constraints using sympy


I’m currently working on a project that requires plotting and equation with constraints like:

sin(x) for x > 1.

but can get more complicated than this like:

3z * cos(x) for x >= 0 and x + z = 1

I managed to take the input as a string and convert it into Sympy equations.

so far the code is like this

import sympy
from sympy.parsing.sympy_parser import parse_expr

# Some other unrelated processing to the input goes here
# eventually we get a string for the equation
# and a list of strings for the constraints

equation = "sin(x)"
constraints = ["x > 1"]

x = sympy.symbols("x") 
eq = parse_expr(equation, evaluate= False)
constraints = [ parse_expr(cons, evaluate= False) for cons in constraints]

Now I want to plot the given equation with the provided constraints, to plot the equation for the valid constraints I tried

sympy.plot_implicit(sympy.And(eq, *constraints))

but it doesn’t work, I get an error: TypeError: expecting bool or Boolean, not sin(x).

Asked By: Abdulrahman Itman



This error: TypeError: expecting bool or Boolean, not sin(x) means that logical operators (And, Or) requires relational objects (equalities or inequalities). Instead, you provided an expression.

You have to wrap your equation into an equality:

sympy.plot_implicit(sympy.And(sympy.Eq(eq, 0), *constraints))

EDIT: now the problem is the visualization. plot_implicit might be good enough to plot lines or regions, but it’s definitely not good ad all at plotting "points".

For example:

plot_implicit(And(Eq(sin(x), 0), x >= 0), grid=False)

This is good enough (albeit, the lines are very thin):
enter image description here

This is an example of not good enough. Note that it is able to capture the points where the expression is satisfied, but they are so small that they are almost invisible:

plot_implicit(And(Eq(3*z*cos(x), 0), x >= 0, Eq(x + z, 1)), (x, -10, 10), grid=False)

enter image description here

Answered By: Davide_sd
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.