The number of lattice points in a circle

I am trying to determine the number of lattice points in a circle, i.e. basically I'm trying to find the number of pairs (m, n) such that m ^ 2 + n ^ 2 <= r ^ 2, where m and n are integers. I used the code below for this, but I get the wrong answer for r = 12, which should be 441 according to this , and I get 121, and I was wondering where I could be wrong:

def latticepoints(N):
    num = 0
    for m in range(0, int(N), 1):
        for n in range(0, int(N), 1):
            if (m**2 + n**2) <= N**2:
                num = num + 1

    return number

print(latticepoints(12))

Edit

Just decided. Just need to change the loops to:

for m in range(-int(N), int(N)+1, 1):
    for n in range(-int(N), int(N)+1, 1):

thanks

+4
source share
1 answer

As you already noted, the problem is that you count the lattice points in one quadrant of the circle. Expanding the range for correction is one approach; an alternative solution is to take

lattice points = 4 * (lattice points in a single quadrant) - 3

3, .


, :

  • range() : , :

    • , 1
    • , 0 1

    , , ( ) – .

    ,

    for m in range(int(N)):
    

    :

    for m in range(-int(N), int(N)):
    

  • N , , int(). int() , . .

  • , , NameError. num, number, . , ; , lattice_count.

    , num = num + 1 num += 1.

  • m > sqrt(N) n > sqrt(N), , (m, n) N. , , -sqrt(N) <= m <= sqrt(N), n.

+2
source

Source: https://habr.com/ru/post/1609407/


All Articles