Skip to content

Commit 2e7c0f5

Browse files
committed
add solution to pi example
1 parent a9e66d3 commit 2e7c0f5

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

_episodes/06-numpy-scipy.md

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -391,6 +391,48 @@ express any other way without using explicit `for` loops.
391391
> You'll want to use `np.random.random` for your random numbers. Take
392392
> a look at the documentation for that function to see what arguments
393393
> 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}
394436
{: .challenge}
395437
396438

0 commit comments

Comments
 (0)