Please help me to draw f(x) = sin(x) if x<=0 and f(x)=cos(x) if x>1
thanks for your answers
There are a few options. One is to use the piecewise
command:
f=Piecewise([[(-10,1),sin(x)],[(1,10),cos(x)]],x)
plot(lambda x: f(x),(-2*pi,2*pi))
Another is to use a python function definition:
def f(x):
if x<=1:
return(sin(x))
else:
return(cos(x))
plot(f,(-2*pi,2*pi))
Note that with the python function definition, the plot
command must be called just with f
and not f(x)
. Calling with f(x)
causes python to evaluate f before doing the plot and will result in an incorrect plot.
More compactly, you could also use a lambda expression: `lambda x: sin(x) if x `<`= 1 else cos(x)`
Please start posting anonymously - your entry will be published after you log in or create a new account.
Asked: 11 years ago
Seen: 2,583 times
Last updated: Jun 12 '13