0

So I have defined a function, and for some reason the terminal is returning the following error:

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

I'm not sure what I have done wrong exactly?

Here is my self-contained function with corresponding plot:

import matplotlib
import math
import numpy
import matplotlib.pyplot as pyplot
import matplotlib.gridspec as gridspec

def rotation_curve(r):
    v_rotation = math.sqrt((r*(1.33*(10**32)))/(1+r)**2)
    return v_rotation

curve_range = numpy.linspace(0, 100, 10000)

fig = pyplot.figure(figsize=(16,6))

gridspec_layout = gridspec.GridSpec(1,1)
pyplot = fig.add_subplot(gridspec_layout[0])

pyplot.plot(curve_range, rotation_curve(curve_range))

matplotlib.pyplot.show()

Could anyone advise me where I have gone wrong?

1
  • please add the full error traceback. Commented Oct 21, 2015 at 16:16

1 Answer 1

1

The problem is in the definition of rotation_curve(r). You input and manipulate a numpy array (curve_range), but you do so using a non-vectorized function math.sqrt:

v_rotation = math.sqrt((r*(1.33*(10**32)))/(1+r)**2)

Instead, use numpy.sqrt which broadcasts the sqrt operation across every element in the array. The multiplication and exponentiation operators are overloaded in numpy arrays, so those should work fine.

def rotation_curve(r):
    v_rotation = numpy.sqrt((r*(1.33*(10**32)))/(1+r)**2)
    return v_rotation
Sign up to request clarification or add additional context in comments.

2 Comments

Closer. It is now giving me the following ValueError: x and y must have same first dimension. Traces back to pyplot.plot(rotation_curve, rotation_curve(curve_range))
Fixed the problem, ignore previous comment.

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.