python 定点运算

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/422247/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 20:03:59  来源:igfitidea点击:

Fixed-point arithmetic

pythonmath

提问by Kurt Pattyn

Does anyone know of a library to do fixed point arithmetic in Python? Or, does anyone has sample code?

有谁知道在 Python 中进行定点运算的库?或者,有人有示例代码吗?

回答by John Mulder

If you are interested in doing fixed point arithmetic, the Python Standard Library has a decimalmodule that can do it.

如果你对定点算术感兴趣,Python 标准库有一个十进制模块可以做到这一点。

Actually, it has a more flexible floating point ability than the built-in too. By flexible I mean that it:

实际上,它也比内置的具有更灵活的浮点能力。灵活我的意思是:

  • Has "signals" for various exceptional conditions (these can be set to do a variety of things on signaling)

  • Has positive and negative infinities, as well as NaN (not a number)

  • Can differentiate between positive and negative 0

  • Allows you to set different rounding schemes.

  • Allows you to set your own min and max values.

  • 具有针对各种特殊情况的“信号”(这些可以设置为在信号上做各种事情)

  • 具有正无穷大和负无穷大,以及 NaN(不是数字)

  • 能区分正负 0

  • 允许您设置不同的舍入方案。

  • 允许您设置自己的最小值和最大值。

All in all, it is handy for a million household uses.

总而言之,对于百万家庭使用来说非常方便。

回答by geschema

The deModelpackage sounds like what you're looking for.

deModel包听起来就像你在找什么。

回答by rwp

Another option worth considering if you want to simulate the behaviour of binaryfixed-point numbers beyond simple arithmetic operations, is the spfpmmodule. That will allow you to calculate square-roots, powers, logarithms and trigonometric functions using fixed numbers of bits. It's a pure-python module, so doesn't offer the ultimate performance but can do hundreds of thousands of arithmetic operations per second on 256-bit numbers.

如果您想模拟除简单算术运算之外的二进制定点数的行为,另一个值得考虑的选项是spfpm模块。这将允许您使用固定位数计算平方根、幂、对数和三角函数。它是一个纯 python 模块,因此不能提供终极性能,但每秒可以对 256 位数字执行数十万次算术运算。