I compute the reverse of matrix A, for instance,
import numpy as np
A = np.diag([1, 2, 3])
A_inv = np.linalg.pinv(A)
print(A_inv)
I got,
[[ 1. 0. 0. ]
[ 0. 0.5 0. ]
[ 0. 0. 0.33333333]]
But, I want this,
[[ 1. 0. 0. ]
[ 0. 1/2 0. ]
[ 0. 0. 1/3]]
I tried np.set_printoptions
,
import fractions
np.set_printoptions(formatter={'all':lambda x: str(fractions.Fraction(x))})
print(A_inv)
but I got this,
[[1 0 0]
[0 1/2 0]
[0 0 6004799503160661/18014398509481984]]
How do I convert decimals to fractions in NumPy?
numpy
to invert the matrix using something likefractions.Fraction
? – Evensonlambda x: str(fractions.Fraction(x).limit_denominator())
– Virgilvirgilia