I'm trying to check if matrix of orthonormal by multiplying matrix with transpose itself.
import numpy as np
matrix = np.array([[np.sqrt(2)/2, -np.sqrt(2)/2],
[np.sqrt(2)/2, np.sqrt(2)/2]])
dot = matrix.T.dot(matrix)
print(dot)
Expected output
[[1. 0.]
[0. 1.]]
Instead of that, I got
[[ 1.00000000e+00 -4.26642159e-17]
[-4.26642159e-17 1.00000000e+00]]
I've tried to use different types: float64, float128, complex128. But answer is still incorrect.
1 Answer 1
That comes from python dividing numbers. This is done in the binary, which produces such a result. You are looking for round() function
matrix = np.array([[round(np.sqrt(2)/2, 2), round(-np.sqrt(2)/2, 2)],
[round(np.sqrt(2)/2, 2), round(np.sqrt(2)/2), 2]])
answered Jul 14, 2020 at 18:05
Aleksander Ikleiw
2,7152 gold badges11 silver badges29 bronze badges
Sign up to request clarification or add additional context in comments.
4 Comments
sushanth
Looks like there is some syntax errror.
Aleksander Ikleiw
@Sushanth thank you for pointing, I have made a typo - I am writing from the phone and did not see that I missed the
]user2357112
You're rounding the wrong matrix (and the choice to round to 2 digits after the decimal point is arbitrary and unexplained).
user2357112
Your parentheses are wrong on the last
round call (and you're still rounding the wrong matrix).lang-py
dot.round(2)-4.26642159e-17is 0. Thee-17on the end means "times 10 to the power of -17".np.sqrt(2)/2is not exactly the square root of two; it has an error due to rounding to the floating-point format. So the test is correctly telling you that the matrix is not orthonormal. You can test whether it is near orthonormal, possibly by testing whether the product of the matrix and its transpose is near the identity matrix. But then (b) you have to define how near is acceptable, as well as defining a metric for "near," and (c) you have to accept that the test will report some non-orthonormal matrices as orthonormal.