python怎么限制输出精度_设置全局输出精度python

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值