How to use numpy arrays with fractions? How to use numpy arrays with fractions? numpy numpy

How to use numpy arrays with fractions?


You can also convert the entire array to an object array of Fraction objects, by abusing the element-wise conversion of numpy arrays under arithmetic operations. (Note: this requires the original array to be an integer array, since arithmetic between floats and Fractions produce floats.)

>>> A = np.array([[-1,  1],[-2, -1]])array([[-1,  1],       [-2, -1]])>>>>>> A.dtypedtype('int64')>>>>>> A = A + Fraction()>>> Aarray([[Fraction(-1, 1), Fraction(1, 1)],       [Fraction(-2, 1), Fraction(-1, 1)]], dtype=object)

With the array in this format, any further arithmetic performed will be over elements of type Fraction.


Since Fractions are not a native NumPy dtype, to store a Fraction in a NumPy array you need to convert the array to object dtype:

import numpy as npfrom fractions import FractionA = np.array([[-1.,  1.],              [-2., -1.]])   # <-- creates an array with a floating-point dtype (float32 or float64 depending on your OS)A = A.astype('object')A[0, 0] = Fraction(2,3)print(A)

prints

[[Fraction(2, 3) 1.0] [-2.0 -1.0]]

PS. As user2357112 suggests, you might be better off using sympy if you wish to use rational numbers. Or, just represent the matrix as a list of lists. There are no speed advantages to using NumPy if your arrays are of object dtype.

import sympy as syA = [[-1.,  1.],     [-2., -1.]]A[0][0] = sy.Rational('2/3')print(A)

prints

[[2/3, 1.0], [-2.0, -1.0]]