0

I am writing a code for doing some integration. But I am stuck at some point(the last two lines). As it says Index Error: Index out of bounds. What I would like to do is- each time r has a value it should write to the empty corresponding index as an increment of 1 so that it can keep track of it. Any help would be appreciated. Here is the code-

from pylab import*
from math import*

dx = 981
dy = 1043
bx = 534.4
by = 109.5

index = zeros(shape=(1,dx+dy))
r=0
r_max=0

for i in xrange(1,dy+1):
    for j in xrange (1,dx+1):
        if i-by > 0:
            theta = 180*atan(abs(j-bx)/(i-by))/pi
            if theta<10:
                r = round(sqrt((j-bx)**2+(i-by)**2))
                if r>0:
                    index[r]+=1
3
  • 2
    Just a general tip: You should (usually) not use from foo import *. It's better to import foo and then call foo.bar(). For example, I was thrown off by zeros() - where is it defined? You can't tell. If you do import pylab and then call pylab.zeros(), it's much easier to understand what is happening. Commented Apr 12, 2013 at 7:56
  • TimPietzcker is absolutely right, this code would start producing weird behaviour if you would add NumPy to it as well (due to the numpy.zeros). Commented Apr 12, 2013 at 8:10
  • will keep that in mind next time. Commented Apr 12, 2013 at 12:14

1 Answer 1

2

When you do index = zeros(shape=(1,dx+dy)) you create a 2-dimensional array, with the first axis of size 1. When you do index[r]+=1 you access that first axis of the array, with index r, which can be > 1.

So it looks like what you want is to get rid of the first "useless" dimension, by doing

index = zeros(shape=(dx+dy))

Or, alternatively, indexing the second axis:

index[0, r]+=1

Or,

index[:, r]+=1
Sign up to request clarification or add additional context in comments.

1 Comment

@user2095624 glad I could help. If you find an answer helpful, feel free to accept it

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.