首页 文章

sympy矩阵元素?

提问于
浏览 433
0

我对宏做错了什么?

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

可能不正确,但至少它是有效的

如果我的一些假设错误,请纠正我 .

1 回答

  • 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
    

相关问题