相关疑难解决方法(0)

在 SymPy 中打印四舍五入到 3 位小数的输出

我有一个 SymPy 矩阵 M

In [1]: from sympy import *
In [2]: M = 1/10**6 * Matrix(([1, 10, 100], [1000, 10000, 100000]))
In [3]: M
Out[3]: 
Matrix([
[1.0e-6, 1.0e-5, 0.0001],
[ 0.001,   0.01,    0.1]])
Run Code Online (Sandbox Code Playgroud)

我想打印四舍五入到 3 位小数的输出,如下所示:

In [3]: M
Out[3]: 
Matrix([
[ 0.000, 0.000, 0.000],
[ 0.001, 0.010, 0.100]])
Run Code Online (Sandbox Code Playgroud)

在普通的 Python 中,我会这样:

In [5]: '{:.3f}'.format(1/10**6)
Out[5]: '0.000'
Run Code Online (Sandbox Code Playgroud)

但是如何在 SymPy 矩阵中做呢?

此外,更一般的情况是一个还包含符号的表达式

x = symbols('x')
M = 1/10**6 * Matrix(([1, 10*x, 100], [1000, 10000*x, 100000]))
Run Code Online (Sandbox Code Playgroud)

首选输出是

In [3]: M
Out[3]: …
Run Code Online (Sandbox Code Playgroud)

python sympy

5
推荐指数
1
解决办法
3112
查看次数

Python float __setformat__?

我有一个问题,我需要得到一个正确的浮点数小数点后18位.当我使用默认浮点数(数字)时,它只给我12个小数位.

然后我做了dir(浮动)

    ['__abs__', '__add__', '__class__', '__coerce__', '__delattr__', '__div__', '__divmod__', '__doc__',
 '__eq__', '__float__', '__floordiv__', '__format__', '__ge__', '__getattribute__', '__getformat__',
 '__getnewargs__', '__gt__', '__hash__', '__init__', '__int__', '__le__', '__long__', '__lt__', '__m
od__', '__mul__', '__ne__', '__neg__', '__new__', '__nonzero__', '__pos__', '__pow__', '__radd__', '
__rdiv__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rmod__', '_
_rmul__', '__rpow__', '__rsub__', '__rtruediv__', '__setattr__', '__setformat__', '__sizeof__', '__s
tr__', '__sub__', '__subclasshook__', '__truediv__', '__trunc__', 'as_integer_ratio', 'conjugate', '
fromhex', 'hex', 'imag', 'is_integer', 'real']
Run Code Online (Sandbox Code Playgroud)

该块中有一些叫做__setformat__的东西.有什么用?以及如何使用它进行浮点精度设置?

我使用的是python 2.7.5 x64.

python floating-point python-2.7

-1
推荐指数
2
解决办法
268
查看次数

标签 统计

python ×2

floating-point ×1

python-2.7 ×1

sympy ×1