r/pythonhelp • • Dec 27 '22

New to python from Matlab. Seem to be getting a strange response

I am used to defining a function in the following method, but unfortunately, it does not seem to be working. Could someone help me out?

x = np.linspace(0, 50, 2001)
for i in range(len(x)):
Vk[i] = 0.5*k*(x[i])^2 -(1/3)*a*(x[i])^3
plt.plot(x, Vk)

3 Upvotes

3 comments sorted by

3

u/jammasterpaz Dec 27 '22

^ is bitwise xor. ** or math.pow is exponentiation.

1

u/DrK1NG Dec 27 '22

Also, you don't need to index using a loop for tasks like this since you're using numpy. You can just do

Vk = 0.5*k*x**2 - (1/3)*a*x**3

Then just

plt.plot(x, Vk)

1

u/[deleted] Dec 28 '22

The issue with your code is that you are using the ^ operator to raise a value to a power. In Python, the ^ operator is used for bitwise XOR, not exponentiation. To raise a value to a power in Python, you can use the ** operator.

Here's an example of how you can fix your code to use the ** operator:
x = np.linspace(0, 50, 2001)
for i in range(len(x)):
Vk[i] = 0.5*k*(x[i])**2 -(1/3)*a*(x[i])**3
plt.plot(x, Vk)