Computational Science Asked by user664 on July 6, 2021
I want to plot
$$f_{n}(x) = begin{cases} x-n & text{for } n leq x leq n+1
2-x+n & text{for } n+1leq x leq n+2
0 & text{otherwise.}
end{cases} $$
How can I plot a piecewise function like this one using open-source software?
#!/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()
Correct answer by GertVdE on July 6, 2021
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 )
.
Answered by Pedro on July 6, 2021
Another option would be to use the matplotlib package in Python. You can create a function f(n, x) that evaluates the function rather easily, and then evaluate it for a set of points. The resulting plot commands are very MATLAB-like, so if you know MATLAB, the work in matplotlib will be quite easy.
If you're a student, you can get a free, easy-to-install academic version of Python with NumPy, matplotlib, and a whole bunch of other packages pre-installed via the Enthought Python Distribution. It's quite useful, and takes out a lot of the guesswork in terms of installing the core Python packages.
Answered by aeismail on July 6, 2021
If you don't really require it to be open-source, nor a program, then you can try Wolfram Alpha.
Answered by Gigi on July 6, 2021
SymPy is able to plot your piecewise function:
from sympy import *
x = Symbol('x')
n = 2 # you have to choose some explicit number for n
f = Piecewise((0, n<=x), (x-n, x<=n+1), (2-x+n, x<=n+1), (0, True))
plot(f)
Answered by MRocklin on July 6, 2021
I think a piecewise function is a perfect case for using a closure. This frees you from the need of having a cumbersome n
as an argument.
import numpy as np
import matplotlib.pyplot as plt
def define_fn(n):
def fn(x):
if n <= x <= n + 1:
return float(x) - n
elif n + 1 <= x <= n + 2:
return 2.0 - x + n
else:
return 0.0
return fn
f3 = define_fn(3)
f8 = define_fn(8)
X = np.linspace(0, 12, 1000)
Y3 = [f3(x) for x in X]
Y8 = [f8(x) for x in X]
plt.plot(X, Y3, label='f3')
plt.plot(X, Y8, label='f8')
plt.legend()
plt.show()
```
Answered by kotchwane on July 6, 2021
Get help from others!
Recent Answers
Recent Questions
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP