Python prevent overflow errors while handling large floating point numbers and integers

2024/11/13 16:09:01

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)

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

enter image description here

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?

Note: I am using python 2.7.

Answer

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

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')

Other libraries are mpmath and gmpy2.

>>> import gmpy2
>>> gmpy2.set_context(gmpy2.context(precision=150))
>>> a=gmpy2.sqrt(5)
>>> a
mpfr('2.2360679774997896964091736687312762354406183598',150)
>>> ((1+a)**100 - (1-a)**100)/(a*(2**100))
mpfr('354224848179261915075.00000000000000000000000248',150)
>>> gmpy2.fib(100)
mpz(354224848179261915075L)

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

Disclaimer: I maintain gmpy2.

https://en.xdnf.cn/q/72047.html

Related Q&A

Python selenium sending keys into textarea

Im using Python 3.4.4 to access a website (https://readability-score.com/) that has a textarea, which dynamically updates when new values are added. Im trying to input a string into that textarea box b…

how to run several executable using python?

I have an executable under linux. I have an 8 core processor. I want to run 8 different instances of the same executable with different arguments.I tried os.system("process_name args")It does…

How to retrieve only arabic texts from a string using regular expression?

I have a string which has both Arabic and English sentences. What I want is to extract Arabic Sentences only.my_string=""" What is the reason ذَلِكَ الْكِتَابُ لَا رَ…

Formatted output in OpenOffice/Microsoft Word with Python

I am working on a project (in Python) that needs formatted, editable output. Since the end-user isnt going to be technically proficient, the output needs to be in a word processor editable format. The …

Issue in calling Python code from Java (without using jython)

I found this as one of the ways to run (using exec() method) python script from java. I have one simple print statement in python file. However, my program is doing nothing when I run it. It neither pr…

AttributeError: tuple object has no attribute dim, when feeding input to Pytorch LSTM network

I am trying to run the following code:import matplotlib.pylab as plt import numpy as np import torch import torch.nn as nnclass LSTM(nn.Module):def __init__(self, input_shape, n_actions):super(LSTM, se…

Python - Idiom to check if string is empty, print default

Im just wondering, is there a Python idiom to check if a string is empty, and then print a default if its is?(The context is Django, for the __unicode__(self) function for UserProfile - basically, I w…

Does WordNet have levels? (NLP)

For example...Chicken is an animal. Burrito is a food.WordNet allows you to do "is-a"...the hiearchy feature.However, how do I know when to stop travelling up the tree? I want a LEVEL. That …

Merge two DataFrames based on columns and values of a specific column with Pandas in Python 3.x

Hello i have a problem which i am not able to implement a solution on. I have following two DataFrames:>>> df1 A B date 1 1 01-2016 2 1 02-2017 1 2 03-2017 2 2 04-2020>>> d…

Use range as a key value in a dictionary, most efficient way?

I have been wondering if there is some kind of data-structure or clever way to use a dictionary (O(1) lookup) to return a value if there are given values for defined ranges that do not overlap. So far …