NumPy:将小数转换为分数 [英] NumPy: convert decimals to fractions

查看:67
本文介绍了NumPy:将小数转换为分数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,我计算矩阵 A 的逆矩阵,

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)

我明白了,

[[ 1.          0.          0.        ]
 [ 0.          0.5         0.        ]
 [ 0.          0.          0.33333333]]

但是,我想要这个,

[[ 1.          0.          0. ]
 [ 0.          1/2         0. ]
 [ 0.          0.          1/3]]

我尝试了 np.set_printoptions

import fractions
np.set_printoptions(formatter={'all':lambda x: str(fractions.Fraction(x))})
print(A_inv)

但是我明白了

[[1 0 0]
 [0 1/2 0]
 [0 0 6004799503160661/18014398509481984]]

如何在NumPy中将小数转换为分数?

How do I convert decimals to fractions in NumPy?

推荐答案

这是一个浮点问题-请记住,在Pythons表示中,2/3并不完全是2/3.

This is a floating point issue - recall that 2/3 is not exactly 2/3 in Pythons representation.

Fraction类具有内置方法 limit_denominator(),可以解决此问题:

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]]

这篇关于NumPy:将小数转换为分数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆