Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NumPy: convert decimals to fractions

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?

like image 440
SparkAndShine Avatar asked Feb 13 '17 16:02

SparkAndShine


People also ask

How do you write fractions in Python?

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.

Does NumPy support decimal?

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.

How do I round up in NumPy?

You can use np. floor() , np. trunc() , np. ceil() , etc. to round up and down the elements of a NumPy array ndarray .


1 Answers

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]]
like image 135
jeremycg Avatar answered Sep 28 '22 08:09

jeremycg