tags:

views:

75

answers:

2

How can I include the upper bound in range() function? I can't add by 1 because my for-loop looks like:

for x in range(1,math.floor(math.sqrt(x))):
    y = math.sqrt(n - x * x)

But as I understand it will actually be 1 < x < M where I need 1 < x <= M Adding 1 will completely change the result. I am trying to rewrite my old program from C# to Python. That's how it looked in C#:

for (int x = 1; x <= Math.Floor(Math.Sqrt(n)); x++)
    double y = Math.Sqrt(n - x * x);
+5  A: 

Just add one to the second argument of your range function:

range(1,math.floor(math.sqrt(x))+1)

You could also use this:

range(math.floor(math.sqrt(x)))

and then add one inside your loop. The former will be faster, however.

As an additional note, unless you're working with Python 3, you should be using xrange instead of range, for idiom/efficiency. More idiomatically, you could also call int instead of math.floor.

jemfinch
+4  A: 

Why exactly can't you simply add one to the upper bound of your range call?

Also, it seems like you want to refer to n in your first line, i.e.:

for x in range(1,math.floor(math.sqrt(n)) + 1):

...assuming you want to have the same behavior as your C# snippet.

zerocrates
+1 for noticing the OP's x-instead-of-n mistake
John Machin