问题
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?
回答1:
This is a floating point issue - recall that 2/3 is not exactly 2/3 in Pythons representation.
The Fraction class has a built in method, limit_denominator()
, to take care of this:
import fractions
np.set_printoptions(formatter={'all':lambda x: str(fractions.Fraction(x).limit_denominator())})
print(A_inv)
Which gives the desired answer:
[[1 0 0]
[0 1/2 0]
[0 0 1/3]]
来源:https://stackoverflow.com/questions/42209365/numpy-convert-decimals-to-fractions