0

I have the following code:

def f(x):
    return x

def g(x):
    return x*x

from math import sqrt
def h(x):
    return sqrt(x)

def i(x):
    return -x

def j(x):
    return -x*x

def k(x):
    return -sqrt(x)

functions = [f, g, h, i, j, k]

And now I'm trying to plot these functions.

I tried

plt.plot(f(x), g(x), h(x))

but I get the following error:

TypeError: only length-1 arrays can be converted to Python scalars

I figure this is because I'm using the square root which has two solutions. But really, I'm trying to do something like:

plt.plot(*functions)

Any advice?

1
  • Please, provide a verifiable example even it's bugged : it shows what you tried so far. Commented Dec 26, 2017 at 15:08

1 Answer 1

3

math.sqrt accepts only scalar values. Use numpy.sqrt to compute the square root of each value in a list or NumPy array:

In [5]: math.sqrt(np.array([0,1]))
TypeError: only length-1 arrays can be converted to Python scalars

In [6]: np.sqrt(np.array([0,1]))
Out[6]: array([ 0.,  1.])

import numpy as np
import matplotlib.pyplot as plt

def f(x):
    return x

def g(x):
    return x*x

def h(x):
    return np.sqrt(x)

def i(x):
    return -x

def j(x):
    return -x*x

def k(x):
    return -np.sqrt(x)

x = np.linspace(0, 1, 100)
functions = [f, g, h, i, j, k]
for func in functions:
    plt.plot(func(x), label=func.__name__)
plt.legend(loc='best')
plt.show()

enter image description here

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.