You can define a piecewise function for certain intervals by using And function to combine conditions:
from sympy import Symbol, Piecewise, And
x = Symbol('x')
p = Piecewise((3, And(0<=x, x<=5)), (5, x>5))
Here I ensured that the function is defined only for 0 <= x <= 5. For x > 5 the function returns 5 and for x < 0, the function is undefined.
python - How to Create Piecewise Function in SymPy with Intervals - Stack Overflow
Sympy how can I plot piecewise function
Are you sure you're running the code you posted? You have misspelt functionleft in the last line and despite the .Piecewise function doc showing it should be called like:
Piecewise( (expr,cond), (expr,cond), ... )
your post shows the third param as a 3-tuple??
More on reddit.comHow to Derivative of piecewise functions using SymPy
plot - Trying graph a piecewise function with Python Sympy, but don't know why all y-values are squeezed into a line - Stack Overflow
import sympy as sp
functionleft = x+2
functionright = x**2
x,y = sp.symbols('x y', real=True)
sp.plot(sp.Piecewise((functionleft, x <= 1) , (functionright, True))Why is this not working? I get TypeError: '<=' not supported between instances of 'complex' and 'int'
Are you sure you're running the code you posted? You have misspelt functionleft in the last line and despite the .Piecewise function doc showing it should be called like:
Piecewise( (expr,cond), (expr,cond), ... )
your post shows the third param as a 3-tuple??
Do you need to define x,y before the functions?
#!/usr/bin/env python
import numpy as np
import matplotlib.pyplot as plt
def fun (n, x):
if n <= x <= n + 1:
return float(x) - n
elif n + 1 <= x <= n + 2:
return 2.0 - x + n
return 0.0
vfun = np.vectorize(fun)
x = np.linspace(0, 10, 1000)
y = vfun(3, x)
plt.plot(x, y, '-')
plt.show()
If you just want to visualize your data, you may try exporting it in a text file to visualize it with gnuplot. For your simple example, you may try to plot it in gnuplot directly as in this example.
In Matlab/Octave, if you have your function as pairs of data x1/y1 and x2/y2, you can plot them using plot( x1 , y1 , x2 , y2 ).

