Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Graph a custom function in python

I would like to graph a custom function including min and max :

import numpy as np
import matplotlib.pyplot as plt

f = lambda x: max(0, x)
x = np.linspace(-10, 10)
y = f(x)

plt.plot(x, y)
plt.show()

Result:

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

Some help will be welcome

like image 380
alex Avatar asked Sep 06 '26 05:09

alex


2 Answers

use vectorized np.clip() instead of f - this way you can set both lower (a_min) and upper (a_max) boundaries in one step:

y = np.clip(x, a_min=0, a_max=None)

or try to vectorize your scalar funcion:

In [146]: x = np.linspace(-1000, 1000, 10**6)

In [147]: x.shape
Out[147]: (1000000,)

In [148]: vf = np.vectorize(f)

In [149]: %timeit [f(i) for i in x]
1.46 s ± 5.42 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

In [150]: %timeit vf(x)
1.03 s ± 8.73 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
like image 81
MaxU - stop WAR against UA Avatar answered Sep 07 '26 19:09

MaxU - stop WAR against UA


Instead of max, use np.maximum:

from matplotlib import pyplot as plt
import numpy as np

f = lambda x: np.maximum(0, x)
x = np.linspace(-10,10)
y = f(x)

plt.plot(x,y)
plt.show()

EDIT:

In case of more complex functions, look out for the numpy equivalents of the functions you intend to use. Most of the time the names are the same as in the math module, e.g. math.sin would become np.sin etc. However, as in the example, max should be replaced by np.maximum not np.max, the latter of which returns the maximum value of an np.ndarray.

like image 29
Thomas Kühn Avatar answered Sep 07 '26 20:09

Thomas Kühn



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!