PI_APPROXIMATION_THREE
The Python program featured in this tutorial web page is a plain-text and command line version of the graphical user interface application featured on the web page at the following Uniform Resource Locator: https://karbytesforlifeblog.wordpress.com/pi_approximation_two/
To view hidden text inside each of the preformatted text boxes below, scroll horizontally.
SOFTWARE_APPLICATION_COMPONENTS
python_source_file: https://raw.githubusercontent.com/karlinarayberinger/KARLINA_OBJECT_extension_pack_27/main/pi_approximation.py
plain_text_file: https://raw.githubusercontent.com/karlinarayberinger/KARLINA_OBJECT_extension_pack_27/main/pi_approximation_output.txt
PROGRAM_INTERPRETATION_AND_EXECUTION
STEP_0: Copy and paste the Python source code into a new text editor document and save that document as the following file name:
pi_approximation.py
STEP_1: Open a Unix command line terminal application and set the current directory to wherever the Python program file is located on the local machine (e.g. Desktop).
cd Desktop
STEP_2: Run the program by entering the following command:
python3 pi_approximation.py
STEP_3: If the program interpretation command does not work, then use the following commands (in top-down order) to install the Python interpreter:
sudo apt update
sudo apt install python3
STEP_4: After running the Python program is booted up and running, it will output pi_approximation statistics once per second until the program stops executing. (The user can terminate the program runtime using the keystoke combination CTRL + C in the command line).
STEP_5: Observe program results on the command line terminal and in the output file. Note that, in order to save computational resources (especially memory space), only the most recent simulation snapshot is written to that file (instead of all snapshots appended to the file in chronological order).
PROGRAM_SOURCE_CODE
Note that, in order to display the Uniform Resource Locator in the Python file on this web page as plain-text, karbytes had to insert a zero-width space Unicode character (​) between the “h” and the “t” in that Uniform Resource Locator. If copy-pasting the Python code from this web page, ensure that the zero-width character is removed after pasting the copied code into a text editor application.
python_source_file: https://raw.githubusercontent.com/karlinarayberinger/KARLINA_OBJECT_extension_pack_27/main/pi_approximation.py
######################################################################################### # file: pi_approximation.py # type: Python # date: 29_DECEMBER_2024 # author: karbytes # license: PUBLIC_DOMAIN ######################################################################################### import random import time """ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ This Python application is a plain-text command line version of the animated JavaScript web application featured on the tutorial web page at the following Uniform Resource Locator: https://karbytesforlifeblog.wordpress.com/pi_approximation_two/ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ """ def is_in_circle(x, y, radius): """Check if a point (x, y) is positioned within a circle of whose radius is centered at (0, 0).""" return x**2 + y**2 <= radius**2 def monte_carlo_simulation(): """Run the Monte Carlo simulation indefinitely, overwriting the log file with the latest snapshot.""" """Note that one of such snapshots is made per second of the simulation.""" red_count = 0 # inside of the circle (which is inscribed inside of a square) blue_count = 0 # outside of the circle (but inside of the square) radius = 200 # equivalent to half the canvas size in pixels output_file = "pi_approximation_output.txt" print("Monte Carlo Simulation for Approximating Pi") print("-" * 50) try: while True: # Generate a random point in the square. x = random.uniform(-radius, radius) y = random.uniform(-radius, radius) # Check if the point lies in the circle. if is_in_circle(x, y, radius): red_count += 1 else: blue_count += 1 # Calculate Pi approximation. total_darts = red_count + blue_count pi_approximation = 4 * (red_count / total_darts) # Convert the result to a string and strip unnecessary trailing zeros pi_approximation_str = f"{pi_approximation:.100f}".rstrip('0').rstrip('.') # Prepare the output string. output = ( f"------------------------------------\n" f"seconds_elapsed: {total_darts}\n" f"red_dot_count: {red_count}\n" f"blue_dot_count: {blue_count}\n" f"Pi approximation: {pi_approximation_str}\n" f"------------------------------------\n" ) # Print to console. print(output, end="") # Overwrite the file with the (second-by-second) latest snapshot. with open(output_file, "w") as file: file.write(output) time.sleep(1) # Wait for 1 second. except KeyboardInterrupt: final_message = "\nThe simulation stopped by the user.\n" print(final_message) with open(output_file, "a") as file: file.write(final_message) print(f"The latest snapshot was saved to {output_file}.") if __name__ == "__main__": monte_carlo_simulation()
SAMPLE_PROGRAM_OUTPUT
The text in the preformatted text box below was generated by one use case of the Python program featured in this computer programming tutorial web page.
plain_text_file: https://raw.githubusercontent.com/karlinarayberinger/KARLINA_OBJECT_extension_pack_27/main/pi_approximation_output.txt
------------------------------------ seconds_elapsed: 3363 red_dot_count: 2647 blue_dot_count: 716 Pi approximation: 3.148379423134106236403795264777727425098419189453125 ------------------------------------ The simulation stopped by the user.
PI_APPROXIMATION_THREE Use Case (Demonstration Video)
The video file linked below shows karbytes using its finished PI_APPROXIMATION_THREE application and via the Unix command line terminal, terminating the program, and checking the program output file.
This web page was last updated on 29_DECEMBER_2024. The content displayed on this web page is licensed as PUBLIC_DOMAIN intellectual property.