forked from rdpeng/ProgrammingAssignment2
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtestCacheMatrix.R
More file actions
56 lines (50 loc) · 1.72 KB
/
testCacheMatrix.R
File metadata and controls
56 lines (50 loc) · 1.72 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# This is a test function for `cachematrix.R`
#
# Test init:
# 1. Create the cached matrix
# 2. Calculate its inverse (inv1) --> this should be slow
#
# Test cases:
# 1. Is the result really an inverse metrix? It should be true that `inv(A)*A = I`.
# 2. Recalculate the inverse (inv2) --> matrix has not changed, it should be
# the same as inv1 and the computations should be very fast,
# i.e., this is the only case when "getting cached data" appears
# 3. Change the matrix A and recalculate the inverse --> matrix has changed,
# however the data are the same, therefore the computation
# should be slow, but the result should be the same as inv1
# 4. Change the matrix again, but this time generate new data with a different
# seed --> matrix has changed, the computation should be slow and the value
# should be different from inv1
#
testCacheMatrix <- function() {
source("cachematrix.R");
set.seed(1);
A <- makeCacheMatrix(matrix(rnorm(100), 10, 10));
inv1 <- cacheSolve(A);
if(sum((inv1 %*% A$get()) - diag(10)) > 2e-9) { # 2e-9 == zeroTol
print("ERROR! inv1 != inverse of A");
} else {
print("OK.");
}
inv2 <- cacheSolve(A);
if(!identical(inv1, inv2)) {
print("ERROR! inv1 != inv2");
} else {
print("OK.");
}
A$set(A$get());
inv3 <- cacheSolve(A);
if(!identical(inv1, inv3)) {
print("ERROR! inv1 != inv3");
} else {
print("OK.");
}
set.seed(2);
A$set(matrix(rnorm(1000), 10, 10));
inv4 <- cacheSolve(A);
if(identical(inv1, inv4)) {
print("ERROR! inv1 == inv3");
} else {
print("OK.");
}
}