非常非常长的小数的算术运算
我一直很好奇:如何对很长的小数执行算术运算——例如,将 pi 计算到小数点后 3000 位(尤其是在命令式语言中)?
I've always been curious: how can I perform arithmetic operations on very long decimals--for example, calculating pi to the 3000th decimal place (especially in an imperative language)?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
使用支持任意精度数字的语言或库......?
在 Python 中,int 会自动提升为任意大小的 long。 您可以使用第二个值来跟踪要移动多少个小数以获得某种任意精度浮点。
在Java中,您可以使用 BigDecimal 类,表示“不可变的、任意精度的有符号十进制数”。
我确信其他语言中也存在其他示例。
Use a language or library that supports arbitrary precision numbers...?
In Python, ints will auto-promote to longs which are arbitrary size. You could use a second value for keeping track of how many decimals to shift over by to get a sort of arbitrary precision floating point.
In Java you could use the BigDecimal class, which represents "Immutable, arbitrary-precision signed decimal numbers".
I'm sure other examples exist in other languages.
对于不支持 bignum 计算的语言,通常有库。 例如,您可以查看GMP。 这些文档将为您提供一些典型算法方法的指导。
快速进行 bignum 算术是很困难的,因此有一些非常复杂的算法......
For languages that don't support computations on bignums, there are often libraries. You might have a look at GMP, for example. The docs will give you pointers to some of the typical algorithmic approaches.
Making bignum arithmetic fast is difficult, so there are some pretty convoluted algorithms out there...
您要么必须在数字级别处理数据(例如增量或确定性地计算每个数字),要么定义具有足够位数以提供足够精度的新数据结构。
You either have to work with the data at the digit level (e.g. calculate each digit incrementally or deterministically) or define new data structures that have a sufficient number of bits to provide adequate precision.