Created
December 9, 2022 11:42
-
-
Save Sparrow0hawk/a12631e3368381d3da6e5928c7aaf99b to your computer and use it in GitHub Desktop.
Playing with ChatGPT
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| from mpi4py import MPI | |
| import numpy as np | |
| # Define the size of the grid | |
| n = 100 | |
| # Initialize MPI and get the rank of the current process | |
| comm = MPI.COMM_WORLD | |
| rank = comm.Get_rank() | |
| # Generate a random starting point for this process | |
| x = np.random.randint(0, n) | |
| y = np.random.randint(0, n) | |
| # Generate a random target point that all processes will search for | |
| if rank == 0: | |
| target_x = np.random.randint(0, n) | |
| target_y = np.random.randint(0, n) | |
| else: | |
| target_x = None | |
| target_y = None | |
| target_x, target_y = comm.bcast((target_x, target_y), root=0) | |
| # Perform the random walk until we find the point | |
| while True: | |
| # Generate a random direction and move in that direction | |
| dx, dy = np.random.choice([(-1, 0), (1, 0), (0, -1), (0, 1)]) | |
| x += dx | |
| y += dy | |
| # Check if we have found the point | |
| if x == target_x and y == target_y: | |
| # If so, stop the random walk and exit the loop | |
| break | |
| # Gather all the random walk steps from all processes into a single array | |
| all_steps = comm.gather((x, y), root=0) | |
| # If this is the root process, print the array of steps | |
| if rank == 0: | |
| print(all_steps) |
Author
Author
This looks great, but doesn't quite work as billed.
The first problem is with line:
dx, dy = np.random.choice([(-1, 0), (1, 0), (0, -1), (0, 1)])This gives an error:
File "<stdin>", line 1, in <module>
File "mtrand.pyx", line 911, in numpy.random.mtrand.RandomState.choice
ValueError: a must be 1-dimensional
You could fix this by using random.choice rather than np.random.choice. I haven't prompted it to use numpy here, but it's interesting that it makes this mistake.
Also more critically, this code doesn't work as intended. As it doesn't halt the search when one MPI worker finds the target. It only breaks the loop on the worker where the target is found. Leading us to a place where this code will only halt once all workers have found the target.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Generated from the following set of queries:
Followed up with: