1

I would like to make matrix which contains fraction numbers, say 1/4, as elements.

I made following matrix:

import numpy as np

alpha = 10
B = np.array([ [0, -0.25, -1/20, alpha/40], [1/(alpha+3), 0, -1/(alpha+3), -(alpha-1)/(alpha+3) ], [ 1/(2*alpha+2), 1/(alpha+1), 0, 1/(10*alpha+10) ], [ -1/2, -9/20, 0, 0 ] ])

print(B)

However, the output is such:

[[ 0.   -0.25 -1.    0.  ]
 [ 0.    0.   -1.   -1.  ]
 [ 0.    0.    0.    0.  ]
 [-1.   -1.    0.    0.  ]]

My question is: How to keep fractions inside matrix for purpose of calculations and functions ? If it wasn't for variable alpha I would convert the values to decimals.

EDIT

The marked dublicate thread does not seem to give solution to this problem:

Here the elements in matrix are assigned from the beginning manually. Whereas in the linked thread elements are assigned to matrix in form of equation. Which makes things messy I think.

flowian
  • 137
  • 12
  • Possible duplicate of [How to use numpy arrays with fractions?](https://stackoverflow.com/questions/42577828/how-to-use-numpy-arrays-with-fractions) – jdehesa Apr 05 '18 at 13:32
  • 2
    For a start you need a package that encodes fractions. Base python and numpy don't do that. They use floats. `sympy` might be your best choice. – hpaulj Apr 05 '18 at 14:47
  • @hpaulj There is a `fractions` module in Python's standard library! – BlackJack Apr 05 '18 at 15:24
  • @BlackJack, In that case you can construct an object dtype array of these `Fractions` objects. But as discussed in [/different-behavior-of-arithmetics-on-dtype-float-object-and-float](https://stackoverflow.com/questions/49662823), numeric calculations with such an array will be hit-or-miss. – hpaulj Apr 05 '18 at 15:40
  • @hpaulj Got any suggestions for encoding package ? – flowian Apr 05 '18 at 16:05

1 Answers1

0

Apparently some thing was done wrongly. However,

B = np.array([ [0, -1/4, -1/20, alpha/40], [1/(alpha+3), 0, -1/(alpha+3), -(alpha-1)/(alpha+3) ], [ 1/(2*alpha+2), 1/(alpha+1), 0, 1/(10*alpha+10) ], [ -1/2, -9/20, 0, 0 ] ])
print(B)

gives valid output now.

flowian
  • 137
  • 12