Issue
I used in Jupyter Notebook the following code (extracted from a larger program):
from sympy import *
import numpy as np
from fractions import Fraction
A = [[0,1,2,3,2,1,0],[2,0,0,1,0,0,0],
[0,0,1,0,0,0,1],[0,1,0,0,0,1,0],
[0,3,3,4,4,2,2],[3,0,0,0,1,0,0]]
a = Matrix(A)
b = a.nullspace()[0]
n = b.shape[0]
listuno = list()
for i in range(n):
#listuno.append(Rational.denominator(b[i])) # for Colab
listuno.append(b[i].denominator) # for Jupyter
xx = np.lcm.reduce(listuno)
xcoef = xx * b
print('Coefficients: ',*xcoef)
When I ran this code in the Google Colab environment I get an error which was solved replacing the line "for Jupyter" with the line "for Colab". Is there a way to have a code that is valid in both environments? Thank you very much for any hint.
Solution
For some reason in Colab b[i].denominator returns function instead of int
# Jupyter:
print("type", type(b[i].denominator)) # type <class 'int'>
# Colab:
print("type", type(b[i].denominator)) # type <class 'method'>
As a workaround you could do if and check if it's int and if not do append b[i].denominator() with function call
den = b[i].denominator
if (type(den)==int):
listuno.append(den)
else:
listuno.append(den())
Here's working code on both
from sympy import *
import numpy as np
from fractions import Fraction
import sys
print("Python version")
print (sys.version)
print("Version info.")
print (sys.version_info)
A = [[0,1,2,3,2,1,0],[2,0,0,1,0,0,0],
[0,0,1,0,0,0,1],[0,1,0,0,0,1,0],
[0,3,3,4,4,2,2],[3,0,0,0,1,0,0]]
a = Matrix(A)
b = a.nullspace()[0]
n = b.shape[0]
listuno = list()
for i in range(n):
den = b[i].denominator
if (type(den)==int):
listuno.append(den)
else:
listuno.append(den())
xx = np.lcm.reduce(listuno)
xcoef = xx * b
print('Coefficients: ',*xcoef)
Answered By - Combinacijus
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.