NumPy: convert decimals to fractions

寵の児 提交于 2021-02-07 07:37:32

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!