python中的默认舍入模式,以及如何将其指定为另一种模式? [英] Default rounding mode in python, and how to specify it to another one?

查看:109
本文介绍了python中的默认舍入模式,以及如何将其指定为另一种模式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Python中默认的四舍五入模式是什么(四舍五入到最接近的等)?以及如何指定呢?

What is the default rounding mode (rounding to nearest, etc) in Python? And how can we specify it?

推荐答案

对于基于IEEE754的平台(如大多数现代平台,包括x86,ARM,MIPS ...),它的默认模式为四舍五入,并与偶数"是Python标准库中唯一可用的模式.这是由标准化默认值提供"的,并且缺少用于更改它的库方法.还有更多不允许更改舍入模式的语言-例如Java-因此这不是孤立的Python异想天开.

With IEEE754-based platform (as most modern ones do, including x86, ARM, MIPS...), it's default mode "round to nearest, ties to even" is the only mode available in Python standard library. That is "provided" by standardized defaults and absense of library methods to change it. There are more languages that doesn't allow to change rounding mode - e.g. Java - so this isn't an isolated Python whim.

实际上,没有太多理由可以更改此设置. IEEE754的直接舍入模式在使用中非常特殊. (我不对坚持默认舍入的方法表示歉意,而只是对它进行评论.)例如,将1e308乘以1e308并舍入为零或减去无穷大会导致大约1.8e308,所以结果也是如此既不是确切答案,也不是基于 POLA 的答案(无穷大).如果您确实需要某些特定的模式来进行计算,请考虑使用特定的库,例如MPFR或gmpy2.

In real, there are too few reasons to change this. Direct rounding modes of IEEE754 are very special in their use. (I don't apologize the approach to stick on the default rounding, but simply comment on it.) For example, multiply of 1e308 by 1e308 with rounding to zero or to minus infinity results in approximately 1.8e308, so, the result is too far both from the exact answer and from POLA-based one (infinity). If you really need some specific modes for your computations, consider using specific libraries, like MPFR or gmpy2.

如果您坚持在不使用专门用于浮点计算的外部模块的情况下进行更改,请尝试通过ctypes模块或模拟量使用C库fesetround,例如此处.同样,您可以选择使用此类骇客并对所有后果负责.我建议将所有带有特殊舍入的代码包装到C级代码,以在函数退出时恢复默认模式.

If you insist on changing this without external modules specialized on floating-point calculations, try using C-library fesetround via ctypes module or analog, e.g. here. Again, it's your choice to use such hacks and become responsible to all consequences. I'd suggest wrapping all pieces with special rounding to C-level code which restores the default mode on function exit.

这篇关于python中的默认舍入模式,以及如何将其指定为另一种模式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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