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?
class fractions. Fraction(string) : This requires the string or unicode instance and a fraction instance with same value is returned. Form for this instance : [sign] numerator ['/' denominator] Here, sign represents '+' or '-' and numerator and denominator are strings of single digits.
NumPy doesn't recognize decimal. Decimal as a specific type. The closest it can get is the most general dtype, object. So when converting the elements to the desired dtype, the conversion is a no operation.
You can use np. floor() , np. trunc() , np. ceil() , etc. to round up and down the elements of a NumPy array ndarray .
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]]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With