0

I am new with Python, This is my code:

import numpy as np

x = [0, 0, 0, 0, 5, 0, 10, 5]
y = [4, 4, 4, 4, 9, 4, 2, 9]

def unitvector1 (x,y):
    looplim=(len(x)+1)

    for i in range (0,looplim):
        z=i+1
        alfa = np.arccos((x[i]*x[z])+(y[i]*y[z])) / ((np.sqrt(x[i] ^ 2+y[i] ^ 2) * np.sqrt(x[z] ^ 2+y[z] ^ 2))) 

        beta =+ (180-alfa)

    return (beta)

temp=unitvector1(x,y)

print(temp)

And I am getting this error:

IndexError: list index out of range

I tried to do it with two for loops but it did not work.

Your help is much needed, Many thanks in advance for your help.

2
  • 1
    looplim shouldn't really be len(x) + 1 since range(0, looplim) will give you a range of 0 to len(x); but while the length of x is len(x), the indices of x is from 0 to len(x) - 1 Commented Feb 15, 2022 at 9:18
  • you can use try and except Commented Feb 15, 2022 at 9:23

4 Answers 4

3

Lists are indexed starting from 0, so for a list of length, say, 13, the last valid index is 12, i.e., 1 less than the length.

When you do looplim=(len(x)+1) and then for i in range (0,looplim), the last value of i is looplim-1 which is equal to len(x), so it's the length rather than 1 less than that.

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

Comments

1
looplim=len(x) 
for i in range(looplim-1):
alfa = np.arccos((x[i]*x[z])+(y[i]*y[z])) / ((np.sqrt(x[i] ^ 2+y[i] ^ 2) * 
np.sqrt(x[z] ^ 2+y[z] ^ 2)))  

for each iteration value of "alfa" is nan

Comments

1

remove + 1 from looplim=(len(x)+1) and z = i+1 then run the code !

2 Comments

Hi thank you for your response, If I will delete z=i+1 I would get a not-defined name. I am not completely following
Hello my friend... i meant you remove + 1 from z variable definition... so your z variable is equal i . Best regards
1

Okay, first u should look at your variable z. When i=7 z=8 and there are no eight’s index element in x array. Second, idk why you try “looplim”. If you want to do operations with n and n+1 elements in this way we can add next:

   def unitvector1 (x,y):
      for i in range (len(x)-1):
          z=i+1
          if z==len(x)+1:
              z=0
          alfa = np.arccos((x[i]*x[z])+(y[i]*y[z])) / ((np.sqrt(x[i] ^ 2+y[i] ^ 2) * np.sqrt(x[z] ^ 2+y[z] ^ 2))) 

          beta =+ (180-alfa)

    return (beta)

But it’s not working! Because arccos(alpha) should have alpha<|1|

If you can explain what do you want to count, maybe we can help you

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.