【问题标题】:Is there any command that enables to set for the whole program the number of decimals in a float variable?是否有任何命令可以为整个程序设置浮点变量中的小数位数?
【发布时间】:2014-02-08 12:52:39
【问题描述】:

如果有人能告诉我是否可以在 Python 中明确设置浮点变量的精度,我将不胜感激。我的意思是像 MATLAB 中的格式的长/短函数。谢谢!

这里是一个例子!

import numpy as np
from matplotlib import pyplot as plt
from mayavi import mlab
import matplotlib.cm as cm
from matplotlib import animation


from decimal import *
setcontext(program_context)
program_context = Context(prec=4, rounding=ROUND_UP)

a=.1
dt=.1

nx=31
ny=31
p=6

x = np.linspace(-p,p,nx)
y = np.linspace(-p,p,ny)


qx=2.0*p/(nx-1)
qy=2.0*p/(ny-1)

ax.set_xlim(-p,p)
ax.set_ylim(-p,p)

X,Y = np.meshgrid(x,y)

U=-a*Y
V=a*X



xp = np.empty(11) 
yp = np.empty(11)

xp[0]=2
yp[0]=2

for i in range(10):

    xp[i+1]=xp[i]+dt*U[i+(2+p)/qx,i+(2+p)/qy]
    yp[i+1]=yp[i]+dt*V[i+(2+p)/qx,i+(2+p)/qy]
    print (xp[i], yp[i])

我得到以下内容:

(2.0, 2.0)
(1.98, 2.02)
(1.956, 2.044)
(1.9279999999999999, 2.0720000000000001)
(1.8959999999999999, 2.1040000000000001)
(1.8599999999999999, 2.1400000000000001)
(1.8199999999999998, 2.1800000000000002)
(1.7759999999999998, 2.2240000000000002)
(1.7279999999999998, 2.2720000000000002)
(1.6759999999999997, 2.3240000000000003)

是否有可能只获得小数部分的 4 个数字?谢谢您的帮助! Strömungsmechanik

【问题讨论】:

  • 您可能想阅读以下内容:docs.python.org/2/tutorial/floatingpoint.html
  • 谢谢托拜厄斯。每次我需要特定格式时,我想要一些比通过命令小数强制格式更实用的东西。我可以像在 MATLAB 中那样为整个程序设置简短的格式吗?谢谢!
  • setcontext(program_context) 必须在声明 program_context 之后,而不是之前。
  • 即使我们把它放在它之后也不会改变任何东西!我认为对每个变量强加 Decimal 太麻烦了!再次感谢你的帮助! :)
  • @Strömungsmechanik:同意必须将每个变量声明为 Decimal 很麻烦。看看 numpy 的 around 函数和我在下面链接到的 SO 答案,这可能很有用,但我对 numpy 的了解还不够确定。

标签: python variables format


【解决方案1】:

不,你不能。 Python 浮点数不允许可自定义的字符串表示 他们总是表示为doubles。格式化它们的唯一方法是显式使用格式字符串(如"{:.4f}".format(1.23456789)"%.4f" % 1.23456789)。

在纯 python 中,您可以使用decimal 模块,它允许您为浮点数设置任意精度。 您可以使用contexts 设置精度。

但是,对此类浮点数的操作可能会非常慢。

如果您使用IPython 作为交互式解释器,它确实提供了一个%precision 魔法,您可以使用它来设置浮点数的打印方式:

In [1]: %precision %.4f
Out[1]: '%.4f'

In [2]: 1.2345678
Out[2]: 1.2346

In [3]: %precision %.10f
Out[3]: '%.10f'

In [4]: 1.123456789
Out[4]: 1.1234567890

(请参阅this 相关问题)。

但是,如果您使用 numpy,您可能会这样做,因为它可以提供类似 MATLAB 的环境,您可以使用 @987654325 设置 its 数字的精度@。

例如:

>>> import numpy as np
>>> np.set_printoptions(precision=6)
>>> np.array([1, 2.123456, 3.123456789])
array([ 1.      ,  2.123456,  3.123457])
>>> np.set_printoptions(precision=10)
>>> np.array([1, 2.123456, 3.123456789])
array([ 1.         ,  2.123456   ,  3.123456789])

请注意,您可以提供自定义浮点格式化程序来实现您喜欢的任何表示。

(但请注意,这只会更改数字的显示方式,而不是用于表示它们的位数。为此指定数组的 dtype)。

【讨论】:

  • 谢谢巴库留。想象一下,我有一个要显示的变量向量 x。命令 print 在小数部分给出 12 个数字。我想知道使用 MATLAB 环境的某种格式是否可以只显示 2 个数字!对于每个组件。提前谢谢!
【解决方案2】:

如果您想在 Python 程序中控制数字的精度,您需要考虑使用 Decimal 数字而不是浮点数。要控制decimal.Decimal 数字的精度,您必须定义一个decimal.Context 对象,然后使用decimal.setcontext 函数激活它。激活上下文后,它将控制特定线程中的所有 decimal.Decimal 数字,除非它被新的 decimal.Context 专门覆盖。

添加:numpy 似乎不能很好地处理十进制数字。 numpy.around 可能更合适,尽管我从未使用过它。有关更多详细信息,请参阅此 SO 答案:Better rounding in Python's NumPy.around: Rounding NumPy Arrays

>>> from decimal import *
>>> # create a `Context` to control decimal point precision
>>> program_context = Context(prec=4)
>>> # activate the `Context`
>>> setcontext(program_context)
>>> # from this point on all decimal numbers will be truncated to 4 decimal places.
>>> # you can control the rounding behaviour when the `Context` is created; for example:
>>> new_program_context = Context(prec=4, rounding=ROUND_UP)
>>> # activate the new `Context`
>>> setcontext(new_program_context)
>>> # other rounding options include: 
>>> # ROUND_CEILING (towards Infinity),
>>> # ROUND_DOWN (towards zero),
>>> # ROUND_FLOOR (towards -Infinity),
>>> # ROUND_HALF_DOWN (to nearest with ties going towards zero),
>>> # ROUND_HALF_EVEN (to nearest with ties going to nearest even integer),
>>> # ROUND_HALF_UP (to nearest with ties going away from zero), or
>>> # ROUND_UP (away from zero).
>>> # note that `Context`s only apply to numbers that are explicitly declared to be `Decimal`
>>> a = Decimal(2)
>>> b = Decimal(3)
>>> a/b # evaluates to Decimal('0.6667')
>>> c = 2
>>> d = 3
>>> c/d # evaluates to the floating point number 0.6666666666666666
>>> # also, if constructing a Decimal number from a float, the float must be passed as
>>> # as a string; eg:
>>> e = Decimal("0.6678") # evaluates to Decimal('0.6678')
>>> f = Decimal(0.6678) 
>>> # f evaluates to Decimal('0.6677999999999999491961943931528367102146148681640625')
>>> # integers, however, can be created directly; eg:
>>> h = Decimal(10) # evaluates to Decimal('10')

http://docs.python.org/2/library/decimal.html?highlight=decimal#decimal

【讨论】:

  • 谢谢超级跳。但是我在您提到的网站中找不到所需的功能。我想要一个允许显示不超过 4 位小数的变量的函数。你能帮我吗?
  • @Strömungsmechanik:我已经用更多细节更新了我的答案,希望能有所帮助。
  • 我试过把这三行放在上面,但是不行!你能看看编辑过的问题吗?我刚刚添加了一个例子!谢谢!
  • @Strömungsmechanik:在您的程序中,您需要定义 a=Decimal("0.1")、dt=Decimal("0.1")、nx=Decimal(31) 等等。请注意,浮点数必须指定为字符串,但整数不需要。
猜你喜欢
  • 1970-01-01
  • 2012-08-16
  • 1970-01-01
  • 2019-03-16
  • 2013-05-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多