NumPy: convert decimals to fractions
Asked Answered
T

1

8

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?

Teplica answered 13/2, 2017 at 16:53 Comment(4)
Are you just talking about the representation when printing it? Or do you actually want numpy to invert the matrix using something like fractions.Fraction?Evenson
@mgilson, just for print purpose.Teplica
you are running into floating point issues, try something like lambda x: str(fractions.Fraction(x).limit_denominator())Virgilvirgilia
@jeremycg, it works:-)Teplica
V
15

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]]
Virgilvirgilia answered 13/2, 2017 at 17:12 Comment(3)
Be aware that limit_denominator is doing something very specific, namely finding the closest rational approximation with denominator not exceeding 1 million. That may or may not be appropriate, depending on the use-case. In particular, it's not going to give particularly good results for very large or very small numbers.Whereof
Many thanks. Do you have any idea to format print each elements into fixed width? I used np.set_printoptions(formatter={'str_kind': '{10s}'.format}, but didn't work.Teplica
how to use a comma as separator instead of spacesGaekwar

© 2022 - 2024 — McMap. All rights reserved.