显示小数点后带有较少位数的numpy矩阵

时间:2017-10-12 09:02:15

标签: python-2.7 numpy

如果我在IDLE光标处输入M以查看矩阵matrix([[ 1.65930000e+03, -2.34000000e+01, 1.50000000e+01, 0.00000000e+00], [ 3.30000000e+00, 1.68600000e+03, -2.17000000e+01, 0.00000000e+00], [ -1.70000000e+00, 5.00000000e+00, 1.69440000e+03, 0.00000000e+00], [ -6.18000000e+01, 7.02000000e+01, -4.18000000e+01, 1.00000000e+00]]) 中的值,我会得到:

print(np.array_str(np.array(M), precision=2))

使用print语句表单this answer仅在我首先将numpy矩阵转换为数组时才有效:

[[ 1.66e+03 -2.34e+01 1.50e+01 0.00e+00] [ 3.30e+00 1.69e+03 -2.17e+01 0.00e+00] [ -1.70e+00 5.00e+00 1.69e+03 0.00e+00] [ -6.18e+01 7.02e+01 -4.18e+01 1.00e+00]]

print(np.array_str(M.astype(np.ndarray), precision=2))

这很有帮助,但是当我想调试时,要做很多打字。在调试期间检查时是否有更快的方法来降低精度?

我也试过这个,但情况要糟糕得多。我喜欢科学符号被删除,但精度已经扩大。

[ matrix([[1659.2999999999988, -23.399999999999995, 14.999999999999995, 0.0]], dtype=object)] [ matrix([[3.3, 1686.0000000000002, -21.700000000000003, 0.0]], dtype=object)] [ matrix([[-1.699999999999999, 5.000000000000001, 1694.4, 0.0]], dtype=object)] [ matrix([[-61.799999999998704, 70.20000000000171, -41.799999999998306, 1.0000000000000002]], dtype=object)]]

@IBOutlet var nameText: UITextField!
@IBOutlet var emailText: UITextField!

var database: Connection!

let usersTable = Table("users")
let id = Expression<Int>("id")
let name = Expression<String>("name")
let email = Expression<String>("email")

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

    //creating tableDatabase

    let createTable = self.usersTable.create {(table) in        
        table.column(self.id, primaryKey: true)
        table.column(self.name)
        table.column(self.email, unique: true)
     }
    do {
        try self.database.run(createTable)
        print("created table")
    }
    catch{
        print(error)
    }

    //-------------------
    //inserting

    let insertUser = self.usersTable.insert(self.name <- nameText.text!, self.email <- emailText.text!)

    do {
        try self.database.run(insertUser)
        print("Inserted user")
    } catch{
        print(error)
    }

    //listing
    let myviewcell = segue.destination as! TableViewController

    print("list tapped")
    do{
        let users = try self.database.prepare(self.usersTable)
        var namedb = String(describing: self.name)
        var eml = String(describing: self.email)

        myviewcell.name.append(namedb)
        myviewcell.email.append(eml)

        /*
        for user in users {
            print("userId: \(user[self.id]), name \(user[self.name]), email: \(user[self.email])")
        }
 */
    }catch{
        print(error)
    }

1 个答案:

答案 0 :(得分:1)

NumPy附带帮助函数,例如set_printoptions,因此您可以使用

 numpy.set_printoptions(precision=x)

设置显示的精度。