Looking for a way to populate a list with random numbers (amount of numbers based on user input)

Viewed 218

I'm looking for a way to find a ratio of the number of random coordinates inside a circle to the number of random coordinates outside of the circle but within a square.

I've generated random coordinates - those that lay inside the circle return as "2," and those that lay outside the circle return as "1." I would like to use these to become items in a list, so that I can find the ratios of "2":"1."

import random
import math 
from collections import Counter
for x_y in range(int(input("Number of points: "))):
    x, y = [(random.randint(0,1001)/1000), 
(random.randint(0,1001)/1000)]
    x = (random.randint(0,1001)/1000)
    y = (random.randint(0,1001)/1000)
    def circle(x,y):
# points outside the circle
      if y**2 + x**2 > 1:
        return str(1)
# points inside the circle
      else:
        return str(2)
    print(circle(x,y))

The problem is that each result will print out on a separate line - if I use the Counter, I guess each line is treated as its own list and I can't do any sort of overall frequency operation. I'm also not sure if I would benefit from using integers. I'm very new to Python so I apologize if I'm missing an easy answer.

1 Answers
import random
import math
from collections import Counter

def circle(x,y):
  # points outside the circle
  if y**2 + x**2 > 1:
    #return str(1)
    return 1
  # points inside the circle
  else:
    #return str(2)
    return 2

list1 = []
for x_y in range(int(input("Number of points: "))):
    x, y = [(random.randint(0,1001)/1000), (random.randint(0,1001)/1000)]
      x = (random.randint(0,1001)/1000)
      y = (random.randint(0,1001)/1000)

    list1.append(circle(x,y))
    print(circle(x,y))

A few comments:

With the code you wrote, the circle function gets re-defined every iteration of your loop. It's better to define it before the loop, so it nly gets defined once.

The circle function in your loop returns a string; I think it's easier if it returns an integer, which then you can convert to string if you need to print it.

To save to list, just make an empty list before the loop, and append the result of the function at the end of every loop.

Then you can use the list as you wish. Hope it helps.

Related