宏在做什么错了?
from sympy import *
from decimal import *
def MyMatrixRound(A):
m = A.shape[0]
n = A.shape[1]
for i in range(m):
for j in range(n):
A[i, j]=round(A[i, j]+0.2,1)
A[i, j] = Decimal(str(A[i, j])).quantize(Decimal('0.01'), rounding=ROUND_HALF_UP)
return A
x = Matrix(4, 3, range(12))
print(x)
print(MyMatrixRound(x))
# Matrix([[0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 10, 11]])
# Matrix([[0.200000000000000, 1.20000000000000, 2.20000000000000], [3.20000000000000, 4.20000000000000, 5.20000000000000], [6.20000000000000, 7.20000000000000, 8.20000000000000], [9.20000000000000, 10.2000000000000, 11.2000000000000]])
#
# I want
# Matrix([[0.2, 1.2, 2.2], [3.2, 4.2, 5.2], [6.2, 7.2, 8.2], [9.2, 10.2, 11.2]])
在此先感谢您,英语不好!
2018-12-11 ------------------------------
FullScript.py
from sympy import *
from decimal import *
def MyMatrixPrint(A,iDec):
var('arr')
if iDec == 0 :
cDec = '0'
elif iDec == 1:
cDec='.1'
elif iDec == 2:
cDec = '.01'
elif iDec == 3:
cDec == '.001'
else:
print("unknown")
m = A.shape[0]
n = A.shape[1]
arr = [[0 for j in range(m+n)] for i in range(m+n)]
cMatrix = "myMatrix([["
for i in range(m):
for j in range(n):
arr[i][j] = Decimal(str(A[i,j])).quantize(Decimal(cDec), rounding=ROUND_HALF_UP)
cMatrix = cMatrix+str(arr[i][j]) + " ,"
cMatrix = cMatrix + "],["
cMatrix = cMatrix + "]"
return cMatrix
x = Matrix(4, 3, range(12))
print(" ",x)
r = x.applyfunc(lambda e: e+.2)
print(MyMatrixPrint(r,1))
# I want a little
# Matrix([[0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 10, 11]])
# myMatrix([[0.2 ,1.2 ,2.2 ,],[3.2 ,4.2 ,5.2 ,],[6.2 ,7.2 ,8.2 ,],[9.2 ,10.2 ,11.2 ,],[]
可能不正确,但至少可以正常工作
如果我的某些假设不正确,请纠正我。
2018-12-21 ------------------------------
How to round Matrix elements in sympy?
from sympy import *
x = Matrix(4, 3, range(12))
x[2, 2]=x[2, 2]+0.2
print(x)
print(x.evalf(3))
# Matrix([[0, 1, 2], [3, 4, 5], [6, 7, 8.20000000000000], [9, 10, 11]])
# Matrix([[0, 1.00, 2.00], [3.00, 4.00, 5.00], [6.00, 7.00, 8.20], [9.00, 10.0, 11.0]])
答案 0 :(得分:1)
您在什么环境下运行此程序?使用Windows命令行,我得到:
>>> x = Matrix(4, 3, range(12))
>>> r=x.applyfunc(lambda e:
... Decimal(str(round(e+.2,1))).quantize(Decimal('.01'),
... rounding=ROUND_HALF_UP))
>>> r[0]
0.200000000000000
>>> r
Matrix([
[0.2, 1.2, 2.2],
[3.2, 4.2, 5.2],
[6.2, 7.2, 8.2],
[9.2, 10.2, 11.2]])
>>> r[0].round(1)
0.2