@@ -391,6 +391,48 @@ express any other way without using explicit `for` loops.
391
391
> You'll want to use `np.random.random` for your random numbers. Take
392
392
> a look at the documentation for that function to see what arguments
393
393
> it takes that will be helpful for this problem.
394
+ >
395
+ >> ## Solution
396
+ >>
397
+ >> Two possible solutions:
398
+ >>
399
+ >> ~~~
400
+ >> import numpy as np
401
+ >>
402
+ >> def numpy_pi_1(number_of_samples):
403
+ >> # Generate all of the random numbers at once to avoid loops
404
+ >> samples = np.random.random(size=(number_of_samples, 2))
405
+ >>
406
+ >> # Use the same np.einsum trick that we used in the previous example
407
+ >> # Since we are comparing with 1, we don't need the square root
408
+ >> squared_distances = np.einsum('ij,ij->i', samples, samples)
409
+ >>
410
+ >> # Identify all instances of a distance below 1
411
+ >> # "Sum" the true elements to count them
412
+ >> within_circle_count = np.sum(squared_distances < 1)
413
+ >>
414
+ >> return within_circle_count / number_of_samples * 4
415
+ >>
416
+ >>
417
+ >> def numpy_pi_2(number_of_samples):
418
+ >> within_circle_count = 0
419
+ >>
420
+ >> xs = np.random.random(size=number_of_samples)
421
+ >> ys = np.random.random(size=number_of_samples)
422
+ >>
423
+ >> r_squareds = xs ** 2 + ys ** 2
424
+ >>
425
+ >> within_circle_count = np.sum(r_squareds < 1)
426
+ >>
427
+ >> return within_circle_count / number_of_samples * 4
428
+ >> ~~~
429
+ >> {: .language-python}
430
+ >>
431
+ >> While these are competitive with each other in performance, which
432
+ >> is the fastest depends on various factors. As always, test your
433
+ >> own specific workloads and hardware setup to see how solutions
434
+ >> perform on them.
435
+ > {: .solution}
394
436
{: .challenge}
395
437
396
438
0 commit comments