File tree Expand file tree Collapse file tree 1 file changed +11
-10
lines changed Expand file tree Collapse file tree 1 file changed +11
-10
lines changed Original file line number Diff line number Diff line change 1
1
"""Assignment - using numpy and making a PR.
2
-
3
2
The goals of this assignment are:
4
3
* Use numpy in practice with two easy exercises.
5
4
* Use automated tools to validate the code (`pytest` and `flake8`)
20
19
21
20
def max_index (X ):
22
21
"""Return the index of the maximum in a numpy array.
23
-
24
22
Parameters
25
23
----------
26
24
X : ndarray of shape (n_samples, n_features)
27
25
The input array.
28
-
29
26
Returns
30
27
-------
31
28
(i, j) : tuple(int)
32
29
The row and columnd index of the maximum.
33
-
34
30
Raises
35
31
------
36
32
ValueError
@@ -39,29 +35,34 @@ def max_index(X):
39
35
"""
40
36
i = 0
41
37
j = 0
42
-
43
38
# TODO
44
-
39
+ # error handling
40
+ if not isinstance (X , np .ndarray ):
41
+ raise ValueError ("The input is not a numpy array" )
42
+ if len (X .shape ) != 2 :
43
+ raise ValueError ("The shape is not 2D" )
44
+ i , j = np .unravel_index (np .argmax (X ), X .shape )
45
45
return i , j
46
46
47
47
48
48
def wallis_product (n_terms ):
49
49
"""Implement the Wallis product to compute an approximation of pi.
50
-
51
50
See:
52
51
https://en.wikipedia.org/wiki/Wallis_product
53
-
54
52
Parameters
55
53
----------
56
54
n_terms : int
57
55
Number of steps in the Wallis product. Note that `n_terms=0` will
58
56
consider the product to be `1`.
59
-
60
57
Returns
61
58
-------
62
59
pi : float
63
60
The approximation of order `n_terms` of pi using the Wallis product.
64
61
"""
65
62
# XXX : The n_terms is an int that corresponds to the number of
66
63
# terms in the product. For example 10000.
67
- return 0.
64
+
65
+ product = 2.0
66
+ for i in range (1 , n_terms + 1 ):
67
+ product *= (4 * i ** 2 ) / (4 * i ** 2 - 1 )
68
+ return product
You can’t perform that action at this time.
0 commit comments