Question

In: Computer Science

This Program is Written in PHYTON In geomrety, the value of π can be estimated from...

This Program is Written in PHYTON

In geomrety, the value of π can be estimated from an infinite series of the form:

π / 4 = 1 - (1/3) + (1/5) - (1/7) + (1/9) - (1/11) + ...

However, there is another novel approach to calculate π. Imagine that you have a dartboard that is 2 units square. It inscribes a circle of unit radius. The center of the circle coincides with the center of the square. Now imagine that you throw darts at that dartboard randomly. Then the ratio of the number of darts that fall within the circle to the total number of darts thrown is the same as the ratio of the area of the circle to the area of the square dartboard. The area of a circle with unit radius is just π square unit. The area of the dartboard is 4 square units. The ratio of the area of the circle to the area of the square is π / 4.

To simulate the throwing of darts we will use a random number generator. The Random module has several random number generating functions that can be used. For example, the function uniform(a, b) returns a floating-point random number in the range an (inclusive) and b (exclusive).

Imagine that the square dart board has a coordinate system attached to it. The upper right corner has coordinates ( 1.0, 1.0) and the lower left corner has coordinates ( -1.0, -1.0 ). It has sides that are 2 units long and its center (as well as the center of the inscribed circle) is at the origin.

A random point inside the dart board can be specified by its x and y coordinates. These values are generated using the random number generator. The way we achieve that is:

xPos = random.uniform (-1.0, 1.0)
yPos = random.uniform (-1.0, 1.0)

To determine if a point is inside the circle its distance from the center of the circle must be strictly less than the radius of the circle. The distance of a point with coordinates ( xPos, yPos ) from the center is math.hypot (xPos, yPos). The radius of the circle is 1 unit.

The program that you will be writing will be called CalculatePI. It will have the following structure:

import math
import random

def computePI ( numThrows ):
  ... 

def main ():
  ...

main()

Your function main() will call the function computePI() for a given number of throws. The function computePI() will simulate the throw of a dart by generating random numbers for the x and y coordinates. You will determine if that randomly generated point is inside the circle or not. You will do this as many times as specified by the number of throws. You will keep a count of the number of times a dart lands within the circle. That count divided by the total number of throws is the ratio π/4. The function computePI() will then return the computed value of PI.

In your function main() you want to experiment and see if the accuracy of PI increases with the number of throws on the dartboard. You will compare your result with the value given by math.pi. The quantity Difference in the output is your calculated value of PI minus math.pi. Use the following number of throws to run your experiment - 100, 1000, 10,000, 100,000, 1,000,000, and 10,000,000. You will call the function computePI() with these numbers as input parameters. Your output will be similar to the following, i.e. the actual values of your Calculated PI and Difference will be different but close to the ones shown:

Computation of PI using Random Numbers 

num = 100        Calculated PI = 3.320000   Difference = +0.178407 
num = 1000       Calculated PI = 3.080000   Difference = -0.061593 
num = 10000      Calculated PI = 3.120400   Difference = -0.021193 
num = 100000     Calculated PI = 3.144720   Difference = +0.003127 
num = 1000000    Calculated PI = 3.142588   Difference = +0.000995 
num = 10000000   Calculated PI = 3.141796   Difference = +0.000204 

Difference = Calculated PI - math.pi

Your output MUST be in the above format. The number of throws must be left-justified. The calculated value of π and the difference must be expressed correctly to six places of decimal. There should be a plus or minus sign on the difference.

Solutions

Expert Solution

This program uses a computional algortihm that implements a method called repeated random sampling to obtain the value of pi.

This algorithm uses a square dartboard of unit = 1 and circle inscribed into the square with same diameter. Then we randomly throw darts on the square, the ratio of number where the dart hits inside the square and the total number of throws gives an estimation of pi.

The given code snippet explains how the algorithm proceeds to calculate the value of pi.

Then we use the inbulit math.pi method to find a difference between the estimated pi and the original pi.

To better visualize the data prettyTable is used for formatting.

(NOTE: The program is ran for number of throws upto 10000, feel free to test it for higher iterations but it will take more time to run as the number increases)

import random 
import math
from prettytable import PrettyTable
  

def computePI(numThrows):
    points_on_circle= 0
    points_on_square= 0
    
    # Total Random numbers generated= possible x 
    # values* possible y values 
    for i in range(numThrows**2): 
    
        # Generate random uniform values for xPos and Ypos in the range -1 and 1
        xPos= random.uniform(-1, 1) 
        yPos= random.uniform(-1, 1) 
    
        # Distance from the origin 
        origin_dist= math.hypot(xPos,yPos)
    
        # Checking if (x, y) lies inside the circle 
        if origin_dist<= 1: 
            points_on_circle+= 1
    
        points_on_square+= 1
    
        # Estimating value of pi
        pi = 4* points_on_circle/ points_on_square 
    
    return pi




def main():

    #change this num according to your liking 10,100,1000,10000
    num = 10000

    #pi estimation
    calculated_pi = computePI(num)

    #difference between calculted pi and math.pi
    difference = calculated_pi - math.pi

    #pretty table to see the output
    table = PrettyTable(['Num',"Calculated PI", "Difference"])
    
    table.add_row([num,round(calculated_pi,6),round(difference,6)])

    print(table)

#caliing main method
main()





  


Related Solutions

This Program is Written in PHYTON In geomrety, the value of π can be estimated from...
This Program is Written in PHYTON In geomrety, the value of π can be estimated from an infinite series of the form: π / 4 = 1 - (1/3) + (1/5) - (1/7) + (1/9) - (1/11) + ... However, there is another novel approach to calculate π. Imagine that you have a dartboard that is 2 units square. It inscribes a circle of unit radius. The center of the circle coincides with the center of the square. Now imagine...
This phyton program takes in three integer parameters and displays them in ascending order. You can...
This phyton program takes in three integer parameters and displays them in ascending order. You can assume that the numbers entered are integers. You CAN'T use lists, min(), max(), or the sort utility. The point is to use if tests. sortThreeIntegers( 39, 2, 5 ) should display: The numbers in order are: 2 5 39 sortThreeIntegers( 14, -12, -1000 ) should display: The numbers in order are: -1000 -12 14 def sortThreeIntegers( x, y, z ): < your code goes...
Please use Phyton to write a program: Write a program that calculates and displays the total...
Please use Phyton to write a program: Write a program that calculates and displays the total bill at a restaurant for a couple that is dining. The program should collect from the couple, cost of each meal, and the percentage of the final cost that they would like to tip. The sales tax in the state where the restaurant exists is 7.5%. Display to the user, line by line: Total Cost of Both Meals Sales Tax in dollars Tip in...
Phyton Login program To start the program each day the manager must login. The main (manager)...
Phyton Login program To start the program each day the manager must login. The main (manager) window will appear with a login, create password, and cancel button. A password must exist for the login button to be enabled. The password is created in a separate window and must be 9 characters or more, and it must have at least on digit, uppercase and lowercase letter. The program will continue to show error messages and prompt for a password until a...
Can you provide a step by step process on how to calculate the estimated value from...
Can you provide a step by step process on how to calculate the estimated value from a decision tree? Can you provide how to calculate the risk value from a decision tree?
This phyton program requires you to prints out the total of a series of positive floating-pointnumbers...
This phyton program requires you to prints out the total of a series of positive floating-pointnumbers entered by the user. The user should be prompted with the message "Enter a floating-point number >= 0:". You do not need to check that the input is a FP number. If the user correctly enters a positive FP number, handle it and prompt the user for the next number with the same message. If the user enters a negative number, your program should...
Explain how the polarity of the solvent can affect a π to π* transition. Why are...
Explain how the polarity of the solvent can affect a π to π* transition. Why are orbitals affected differently?
Phyton Exercise 3 Write a program that could evaluate the relationship between two values. User is...
Phyton Exercise 3 Write a program that could evaluate the relationship between two values. User is to key in the two values, and it will be stored in variable, num1 and num2. The program will do a comparison between the two values. If num1 is greater than num2, a message will be display on screen to indicate that num1 is greater than num2. The program will also display appropriate messages when num2 is greater than num1; and num1 is equal...
Phyton Question: You have been hired to create a program that computes that Monthly Net Pay...
Phyton Question: You have been hired to create a program that computes that Monthly Net Pay for a worker after acquiring from the user their Annual Gross Salary. The deductions that are to be considered are an Income Tax of 22.5%, a Social Security Tax of 6.2%, and a Medicare Tax of 1.45%. The program should end by displaying the Monthly Net Pay to the user. Design the algorithm for this program using your preferred method of representation (Pseudocode OR...
Use Laplace transform to solve the initial value problem y''+y'= π with y(0) = π, y'(0)...
Use Laplace transform to solve the initial value problem y''+y'= π with y(0) = π, y'(0) = 0.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT