Меню

Overflowerror integer division result too large for a float ошибка

Необходимо вычислить арктангенс с одним очень большим (относительно другого) катетом.
Выдается ошибка OverflowError: integer division result too large for a float
Как сделать чтоб ответ округлялся до заданного кол-ва знаков после запятой и таким образом обойти эту ошибку.
Спасибо

from math import atan
Катет1 = 10**1000
Катет2 = 10
alpha1 = atan(Катет1/Катет2)
print(alpha1)

Ответы (3 шт):

from math import atan
Катет1 = 10**1000
Катет2 = 10
alpha1 = round(atan(Катет1/Катет2), [кол-во знаков после запятой])
print(alpha1)

Как вы поняли round(x, n) округляет x до заданного n знаков после запятой.
Данный метод не исправляет ошибку, исправить ее округляя нельзя, у python есть определенный размер ограничения чисел после плавающей точки, решается только n // n2 который делит число нацело.

→ Ссылка

Автор решения: pagislav

from math import atan
from decimal import Decimal

cat1 = Decimal(10**1000)
cat2 = Decimal(10)

alpha1 = atan(cat1 / cat2)
print(alpha1)

Вы можете обойти переполнения с помощью Decimal. И округление не понадобится

→ Ссылка

Автор решения: CrazyElf

Ещё вариант решения с помощью библиотеки Numpy:

import numpy as np

cat1 = np.float128(10**1000)
cat2 = 10

alpha1 = np.arctan(cat1 / cat2)
print(alpha1)

Вывод:

1.5707963267948966193

→ Ссылка

context:

I really can’t stress this is just a bit of fun that I have been working on. it is not a production piece of software.

I am using the Mersenne Prime M(n) = 2^n − 1 and Collatz conjecture just for fun to see what would happen. However, I have got to ~1050 for n and I have now run into an error of

Mersenne_Prime=Mersenne_Prime/2

OverflowError: integer division result too large for a float.

The question:

Have I hit just a physical limit of my laptop or is this an issue with my code?

my program is only small

=====================================================================

def main(): #define out main program here

Output_File=open('E:\output.txt','w')

Power_N=float(input("Give me a value of n: "))

Mersenne_Prime=int((2**Power_N)-1)

Steps_Taken=0
while Mersenne_Prime!=1:

	if Mersenne_Prime%2==0:

		print("The number {0} is even".format(Mersenne_Prime),file=Output_File)

		Mersenne_Prime=float(Mersenne_Prime/2)

		Steps_Taken+=1

	else:

		print("The number {0} is odd".format(Mersenne_Prime),file=Output_File)

		Mersenne_Prime=float((Mersenne_Prime*3)+1)

		Steps_Taken+=1

print("The number has reached {0} in {1} steps.".format(Mersenne_Prime,Steps_Taken),file=Output_File)

Output_File.close()

if __name__ == ‘__main__’:

main() # run the program

=====================================================================

it is the line I highlighted that seems to causing issues.

doing

>>> import sys 
>>> sys.float_info.max

in pyhton gives

1.7976931348623157e+308

Question :

How to manage division of huge numbers in Python?

I have a 100 digit number and I am trying to put all the digits of the number into a list, so that I can perform operations on them. To do this, I am using the following code:

for x in range (0, 1000):
   list[x] = number % 10
   number = number / 10

But the problem I am facing is that I am getting an overflow error something like too large number float/integer. I even tried using following alternative

number = int (number / 10)

How can I divide this huge number with the result back in integer type, that is no floats?

Answer #1:

In Python 3, number / 10 will try to return a float. However, floating point values can’t be of arbitrarily large size in Python and if number is large an OverflowError will be raised.

You can find the maximum that Python floating point values can take on your system using the sys module:

>>> import sys
>>> sys.float_info.max
1.7976931348623157e+308

To get around this limitation, instead use // to get an integer back from the division of the two integers:

number // 10

This will return the int floor value of number / 10 (it does not produce a float). Unlike floats, int values can be as large as you need them to be in Python 3 (within memory limits).

You can now divide the large numbers. For instance, in Python 3:

>>> 2**3000 / 10
OverflowError: integer division result too large for a float

>>> 2**3000 // 10
123023192216111717693155881327...

Answer #2:

If you have an integer and you want each digit in a list, you can use:

>>> map(int,list(str(number)))
[1, 5, 0, 3, 0, 0, 7, 6, 4, 2, 2, 6, 8, 3, 9, 7, 5, 0, 3, 6, 6, 4, 0, 5, 1, 2, 4, 3, 7, 8, 2, 5, 2, 4, 4, 5, 4, 8, 4, 0, 6, 6, 4, 5, 0, 9, 2, 4, 8, 9, 2, 9, 7, 8, 7, 3, 9, 9, 9, 7, 0, 1, 7, 4, 8, 2, 4, 4, 2, 9, 6, 9, 5, 1, 7, 1, 3, 4, 8, 5, 1, 3, 3, 1, 7, 9, 0, 1, 0, 1, 9, 3, 8, 4, 2, 0, 1, 9, 2, 9]

it transform the int into a string, then list will take each character of the string and put it in a list. Finally, map will convert each item of the list into an int again

Answer #3:

Python will automatically handle large ints of arbitrary length. What it won’t do is handle floats of arbitrary length so you need to make sure you’re not getting floats along the way.

Answer #4:

Try int(number) % 10. You can only mod integers.

Answered By: erip

Crash Report

This crash report was reported through the automatic crash reporting system 🤖

Traceback

  File "site-packageselectron_cash-3.3.2-py3.5.eggelectroncash_guiqtmain_window.py", line 988, in save_payment_request
  File "site-packageselectron_cash-3.3.2-py3.5.eggelectroncash_guiqtutil.py", line 470, in update
  File "site-packageselectron_cash-3.3.2-py3.5.eggelectroncash_guiqtrequest_list.py", line 88, in on_update
  File "site-packageselectron_cash-3.3.2-py3.5.eggelectroncashwallet.py", line 1486, in get_sorted_requests
  File "site-packageselectron_cash-3.3.2-py3.5.eggelectroncashwallet.py", line 1486, in <lambda>
  File "site-packageselectron_cash-3.3.2-py3.5.eggelectroncashwallet.py", line 1341, in get_payment_request
  File "site-packageselectron_cash-3.3.2-py3.5.eggelectroncashutil.py", line 411, in format_satoshis

OverflowError: integer division result too large for a float

Reporter

This issue was reported by 1 user(s):

Electron Cash Version Python Version Operating System Wallet Type Locale
3.3.2 3.5.4 (v3.5.4:3f56838, Aug 8 2017, 02:07:06) [MSC v.1900 32 bit (Intel)] Windows-10-10.0.17134 standard en_GB

Additional Information

The reporting user(s) did not provide additional information.


By Lenin Mishra
in
python

Jan 23, 2022

Handle Overflow Error exception in Python using the try-except block.

OverflowError Exception in Python

Overflow Error in Python

An OverflowError exception is raised when an arithmetic operation exceeds the limits to be represented. This is part of the ArithmeticError Exception class.


Example 1

Code

j = 5.0

for i in range(1, 1000):
    j = j**i
    print(j)

Output

5.0
25.0
15625.0
5.960464477539062e+16
7.52316384526264e+83
Traceback (most recent call last):
  File "some_file_location", line 4, in <module>
    j = j**i
OverflowError: (34, 'Result too large')

As you can see, when you are trying to calculate the exponent of a floating point number, it fails at a certain stage with OverflowError exception. You can handle this error using the OverflowError Exception class in Python.


Example 2 — Handling OverflowError in Python

Code

j = 5.0

try:
    for i in range(1, 1000):
        j = j**i
        print(j)
except OverflowError as e:
    print("Overflow error happened")
    print(f"{e}, {e.__class__}")

Output

5.0
25.0
15625.0
5.960464477539062e+16
7.52316384526264e+83
Overflow error happened
(34, 'Result too large'), <class 'OverflowError'>

Check out other Python Built-in Exception classes in Python.

built-in-exception-classes — Pylenin

A programmer who aims to democratize education in the programming world and help his peers achieve the career of their dreams.

Я решал вопрос программирования, где мне требовалось найти деление с плавающей запятой очень большого числа (10 ^ 100 000) на другое число (10 ^ 5). Однако, когда я импортировал пол из математического модуля, он выдавал ошибку во время выполнения, но когда я попытался сделать то же самое с помощью //, он показал мне результат.

Я хочу знать, почему такая разница? В чем разница между // и math.floor ().

Я новичок и не могу найти материалы по теме.

С помощью

Используя math.floor


>>> import math
>>> math.floor( pow(10,1000) / 1000 )
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
OverflowError: integer division result too large for a float

С использованием //

pow(10,1000) // 1000
10000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000

3 ответа

Это потому, что pow(10,1000) / 1000 — это деление с плавающей запятой , а pow(10,1000) // 1000 целочисленное деление .

Как видите, в вашем случае integer division result [is] too large for a float, потому что pow(10,1000) / 1000 пытается создать число с плавающей запятой, но результатом будет 10**997, что не поместится даже в 64-битное число с плавающей запятой. Формат с плавающей запятой двойной точности (также известный как «binary64») имеет фиксированную ширину и позволяет хранить числа до 10**308. Если вы все равно хотите сохранить этот номер, вам нужно будет использовать формат binary80. , которого нет в Python прямо из коробки, и, возможно, он все еще не сможет точно представить результат.

Целочисленное деление в Python отличается, потому что тип int ограничен исключительно вашей оперативной памятью. Например, Python может вычислить целое 10**10000 (которое равно your_huge_number ** 10!) В мгновение ока.


4

ForceBru
11 Июл 2019 в 19:39

pow(10, 1000) возвращает целое число.

pow(10, 1000) / 1000 выдает ошибку, поскольку ему необходимо преобразовать pow(10, 1000) в число с плавающей запятой, что невозможно, поскольку оно слишком велико.

pow(10, 1000) // 1000 выполняет целочисленное деление, которое не требует преобразования в число с плавающей запятой.


1

Jmonsky
11 Июл 2019 в 19:35

OverflowError: integer division result too large for a float

Это говорит вам почти все, что вам нужно знать.

\ — целочисленное деление. Python изначально будет использовать вычисления с большими целыми числами, когда числа становятся очень большими, как в этом вопросе.

Однако pow() возвращает числа с плавающей запятой. Они соответствуют строгому стандарту, определяющему формат в памяти, ограничивая возможный диапазон. Значение, которое вы пытаетесь вычислить, выходит за пределы этого диапазона, отсюда и ошибка.


-1

Baldrickk
11 Июл 2019 в 19:34

0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии

А вот еще интересные материалы:

  • Яшка сломя голову остановился исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного где ошибка
  • Overclocking failed ошибка при загрузке
  • Over ошибка на весах