mercredi 3 janvier 2024

Given a RNG in python, Estimate Pi [closed]

I recently watched a popular youtube video that posed the question:

Given a random number in [0,1], write a python program that estimates pi

Before the video gave their solution I came up with the following:

import random 
import math

a=0

n = int(input("Please specificy a number: \n"))

for i in range(n):
    x_i = random.random()
    y_i = random.random()
    d_i = math.sqrt((x_i)**2 + (y_i)**2)
    if d_i <= 1:
        a=a+1


print(4*(a/n))

I watched the rest of the video and my answer was logically equivalent with just some minor differences in syntax. My background is in mathematics so I was able to come up with the mathematical solution that yielded some pseudocode, but I am a very novice programmer so then I googled my way through turning the pseudocode into functional python code. My question for you! experienced users and programmers is: can you tell me a logically equivalent solution to mine that would be preferred if you saw it at work?

Now, I know that is a subjective question that could depend on situation, style, and preference, so let me try to make this question more fit for the community:

Please re-write the above program and point out why yours has superior:

  • elegance
  • readability
  • speed
  • utilization of improvements in python language
  • robustness



Aucun commentaire:

Enregistrer un commentaire