设置全局输出精度python [英] Set global output precision python

查看:820
本文介绍了设置全局输出精度python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经写了一个函数库,使我的工程作业更容易,并在python解释器(有点像计算器)中使用它们。一些返回矩阵,一些返回浮点数。

问题是,他们返回太多的小数。例如,当前,当一个数字为0时,我得到一个非常小的数字作为返回(例如6.123233995736766e-17)。我知道如何单独格式化输出,但是这需要为我在解释器中输入的每一行添加一个格式化程序。我使用的是Python 2.6。

是否有一种方法可以设置会话的全局输出格式(精度等)?

注意:对于scipy函数,我知道我可以使用

  scipy.set_printoptions(precision = 4,suppress = True)

为不使用scipy的函数工作。

解决方案

你所看到的是十进制浮点数只能是通过二进制浮点来近似。请参阅浮点运算:问题和限制



你可以在你的库中放置一个模块级的变量,并将它作为 round()的第二个参数来四舍五入函数的返回值如果你使用 ipython

a>(我推荐交互式使用,比常规解释器更好),你可以使用'魔术'功能
%precision


I've written a library of functions to make my engineering homework easier, and use them in the python interpreter (kinda like a calculator). Some return matrices, some return floats.

The problem is, they return too many decimals. For example, currently, when a number is 0, I get an extremely small number as a return (e.g. 6.123233995736766e-17)

I know how to format outputs individually, but that would require adding a formatter for every line I type in the interpreter. I'm using python 2.6.

Is there a way to set the global output formatting (precision, etc...) for the session?

*Note: For scipy functions, I know I can use

scipy.set_printoptions(precision = 4, suppress = True)

but this doesn't seem to work for functions that don't use scipy.

解决方案

What you are seeing is the fact that decimal floating point numbers can only be approximated by binary floating point. See Floating Point Arithmetic: Issues and Limitations.

You could put a module-level variable in your library and use that as the second parameter of round() to round off the return value of the functions in your module, but that is rather drastic.

If you use ipython (which I would recommend for interactive use, much better than the regular interpreter), you can use the 'magic' function %precision.

这篇关于设置全局输出精度python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆