设置全局输出精度python

编程入门 行业动态 更新时间:2024-10-25 21:29:09
本文介绍了设置全局输出精度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

本文发布于:2023-07-05 06:52:29,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1034349.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:全局   精度   python

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!