Python在处理大型浮点数和整数时防止溢出错误 [英] Python prevent overflow errors while handling large floating point numbers and integers

查看:111
本文介绍了Python在处理大型浮点数和整数时防止溢出错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用python程序来计算斐波那契数列中的数字.这是我的代码:

I am working on a python program to calculate numbers in the Fibonacci sequence. Here is my code:

import math
def F(n):
    return ((1+math.sqrt(5))**n-(1-math.sqrt(5))**n)/(2**n*math.sqrt(5))
def fib(n):
    for i in range(n):
        print F(i)

我的代码使用以下公式在斐波那契数列中查找第N个数字:

My code uses this formula for finding the Nth number in the Fibonacci sequence:

这可以计算斐波那契数列中的许多数字,但我确实会发生溢出错误.

This can calculate many of the the numbers in the Fibonacci sequence but I do get overflow errors.

如何改进此代码并防止溢出错误?

How can I improve this code and prevent overflow errors?

注意:我使用的是python 2.7.

Note: I am using python 2.7.

推荐答案

Python的整数是任意精度的,因此,如果您使用中介算法计算斐波那契数列,则可以计算出准确的结果.

Python's integers are arbitrary precision so if you calculate the Fibonacci sequence using an interative algorithm, you can compute exact results.

>>> def fib(n):
...   a = 0
...   b = 1
...   while n > 0:
...     a, b = b, a + b
...     n = n - 1
...   return a
... 
>>> fib(100)
354224848179261915075L

有多个可用于Python的多精度浮点库. decimal 模块包含在Python中,最初是用于财务计算的.它确实支持 sqrt(),因此您可以执行以下操作:

There are several multiple precision floating-point libraries available for Python. The decimal module is included with Python and was originally intended for financial calculations. It does support sqrt() so you can do the following:

>>> import decimal
>>> decimal.setcontext(decimal.Context(prec=40))
>>> a=decimal.Decimal(5).sqrt()
>>> a
Decimal('2.236067977499789696409173668731276235441')
>>> ((1+a)**100 - (1-a)**100)/(a*(2**100))
Decimal('354224848179261915075.0000000000000000041')

其他库是 mpmath gmpy2 也可以直接计算斐波那契数字(如上所示).

gmpy2 can also computer Fibonacci numbers directly (as shown above).

免责声明:我维护 gmpy2 .

这篇关于Python在处理大型浮点数和整数时防止溢出错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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