0

I am trying to plot a simple function in python ( x + sqrt(x^2 + 2x) ). Here is my code:

import pylab as pl
import numpy as np
import math
X = np.linspace(-999999,999999)
Y = (X+math.sqrt(X**2+2*X))
pl.plot(X,Y)
pl.show()

Here is the error that I am facing: TypeError: only length -1 arrays can be converted to Python scalars

2 Answers 2

1

use

Y = [(x+math.sqrt(x**2+2*x)) for x in X]

or

Y = map(lambda x: (x+math.sqrt(x**2+2*x)), X)

to generate a list of y-values.

You can also vectorize your function and apply it. See List comprehension, map, and numpy.vectorize performance for additional remarks.

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

1 Comment

why not Y = X+np.sqrt(X**2+2*X) ?
0

The problem with your approach is that the math.sqrt function expects a single number as an input. Since you have a numpy-array with more than one element you should use the built-in numpy function sqrt as suggested by Rory Yorke i.e.

Y = X+np.sqrt(X**2+2*X

Since the numpy function is much more optimized it gives you a better performance, for example:

X = np.arange(10000)
timeit Y = map(lambda x: (x+math.sqrt(x**2+2*x)), X)
10 loops, best of 3: 82.1 ms per loop
timeit Y = X+np.sqrt(X**2+2*X) 
10000 loops, best of 3: 108 µs per loop

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.