1

I have a problem that I was not able to solve related to python arrays:

I have the following array x = [n1, n2, n3] I want to increment it the following way:

while x[0] < R:
   while x[1] < R:
     if np.sqrt(x[0] ** 2 + x[1] ** 2 + x[2] ** 2) < R:
        x[2] = x[2] + dx           
        counter = counter + 1
     else:
        
        x[1] = x[1] + dx
        length = dx
print(counter)
x[0] = x[0] + dx
x[1] = dx

This code will do the following:

example: for dx=0.1 and R=1 and we start with 0.1

start with x=[0.1, 0.1, 0.1] (after the first loop) x=[0.9, 0.1, 0.1] And then [0.1, 0.2, 0.1] And so on until [0.9, 0.9, 0.1] After we will get [0.1,0.1,0.2] And we will start again with [0.2, 0.1, 0.2] and so on

I want to extend this idea to any number of dimensions, but I am somehow stuck and any help would be much appreciated

2
  • What is the problem exactly? You say you want to increment and that you are stuck. How? What is not working the way you want. Is it the "any number of dimensions" that is the problem? Commented Feb 1, 2018 at 23:04
  • The problem is a bit more complicated than that. I want to approximate the volume of a hypersphere with by putting small cubes inside of them. So I have thought of the case of 3 dimensions, by summing over all the cubes and making sure they do not "get out" of the sphere by assuring that (x1^2+x2^2+x3^2<R) and each increment as if I am going in a new dimension: and to get the total volume of the sphere, I have to multiply the side length of one sphere^3*counter*8 (I multiply by 8 because I am calculating the cubes only in the positive part of the sphere) Commented Feb 1, 2018 at 23:11

1 Answer 1

1

You can use this, and adapt the repeat value:

from itertools import product

values = [x*.1 for x in range(1, 10)]
for X in product(values, repeat=3):
    print(['%.1f' % x for x in X])

# ['0.1', '0.1', '0.1']
# ['0.1', '0.1', '0.2']
# ['0.1', '0.1', '0.3']
# ['0.1', '0.1', '0.4']
#     
# ['0.1', '0.9', '0.9']
# ['0.2', '0.1', '0.1']
# ['0.2', '0.1', '0.2']
# ['0.2', '0.1', '0.3']
# 
# ['0.9', '0.9', '0.7']
# ['0.9', '0.9', '0.8']
# ['0.9', '0.9', '0.9']
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! But for some reason this is not working for values smaller than 0.1 (for example 0.01 and smaller values) the iterations get somehow completely different

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.