Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Include upper bound in range()

Tags:

python

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);
like image 308
Jull Avatar asked May 07 '10 00:05

Jull


People also ask

Does range include upper bound?

Every non-empty range has two bounds, the lower bound and the upper bound. All points between these values are included in the range. An inclusive bound means that the boundary point itself is included in the range as well, while an exclusive bound means that the boundary point is not included in the range.

How do you make a range inclusive in Python?

Inclusive Range The Python range() function produces a range of values that does not include the last value by default. For example range(0,5) produces a range of values 0, 1, 2, 3, 4. To create an inclusive range, that is, to add the stop value into the range too, add the step value to the stop value.

What is upper bound in Python?

The initial lower bound is index 0 and the initial upper bound is the last index of the sequence.

What is upper bound in function?

Geometrically, an upper bound is. a horizontal line that the graph of the function does not go above. Similarly, a lower bound is a horizontal line that the graph does not go. below. A bound in absolute value 'traps' the graph of the function in.


2 Answers

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.

like image 142
jemfinch Avatar answered Nov 09 '22 18:11

jemfinch


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.

like image 45
John Flatness Avatar answered Nov 09 '22 19:11

John Flatness