Integer division result too large for a float как исправить

С делением через /, действительно, эта ошибка повторяется, но не потому, что он не может делить, а потому, что исходное делимое слишком велико для помещения в double (даже с неизбежной погрешностью), а при / оба числа конвертируются в double (в Python — float) перед собственно делением. Вызвать float() на него тоже даёт ту же ошибку.

С делением нацело — знак // — проблем нет, результат возвращается и корректный:

>>> 4858450636189713423582095962494202044581400587983244549483093085061934704708809928450644769865524364849997247024915119110411605739177407856919754326571855442057210445735883681829823754139634338225199452191651284348332905131193199953502413758765239264874613394906870130562295813219481113685339535565290850023875092856892694555974281546386510730049106723058933586052544096664351265349363643957125565695936815184334857605266940161251266951421550539554519153785457525756590740540157929001765967965480064427829131488548259914721248506352686630476300//3
1619483545396571141194031987498067348193800195994414849827697695020644901569603309483548256621841454949999082341638373036803868579725802618973251442190618480685736815245294560609941251379878112741733150730550428116110968377064399984500804586255079754958204464968956710187431937739827037895113178521763616674625030952297564851991427182128836910016368907686311195350848032221450421783121214652375188565312271728111619201755646720417088983807183513184839717928485841918863580180052643000588655988493354809276377162849419971573749502117562210158766

Если у вас деление нацело тоже не работает — возможно, у вас как-то очень странно скомпилирован сам Python. В таком случае, вам следует рассмотреть смену версии и/или поставщика.

Я проверял оба случая на Python 3.6 под Ubuntu 18.04/x86_64 и Python 3.7 на FreeBSD/i386, так что обычные проблемы 32/64 явно не влияют. Windows под рукой нет, может быть, её странности недостаточно отражены в коде интерпретатора (например, то, что long в 64-битном режиме — 32 бита, противоречит не только устоявшимся традициям всех остальных, но и собственной же .NET).

P.S. Тут есть вопрос, который, возможно, требует жалобы на баг:

>>> float(4858450636189713423582095962494202044581400587983244549483093085061934704708809928450644769865524364849997247024915119110411605739177407856919754326571855442057210445735883681829823754139634338225199452191651284348332905131193199953502413758765239264874613394906870130562295813219481113685339535565290850023875092856892694555974281546386510730049106723058933586052544096664351265349363643957125565695936815184334857605266940161251266951421550539554519153785457525756590740540157929001765967965480064427829131488548259914721248506352686630476300)
Traceback (most recent call last):
  File "", line 1, in 
OverflowError: int too large to convert to float
>>> float('1e+308')
1e+308
>>> float('1e+309')
inf
>>> float('4858450636189713423582095962494202044581400587983244549483093085061934704708809928450644769865524364849997247024915119110411605739177407856919754326571855442057210445735883681829823754139634338225199452191651284348332905131193199953502413758765239264874613394906870130562295813219481113685339535565290850023875092856892694555974281546386510730049106723058933586052544096664351265349363643957125565695936815184334857605266940161251266951421550539554519153785457525756590740540157929001765967965480064427829131488548259914721248506352686630476300')
inf

такое неровное поведение требует как минимум обсуждения его целесообразности.

Необходимо вычислить арктангенс с одним очень большим (относительно другого) катетом.
Выдается ошибка 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

→ Ссылка

I’ve been trying to make a python script that tells if a number is a prime number or not. I’ve tried by my own way, but I ran into a big problem.

When I’m trying to divide a big number it gives me a error OverflowError: integer division result too large for a float. I found that if I use // method at the divide it stops giving me that error, but I can’t find a way to find if the number is prime.

This is the first script I made, that gave the OverflowError: integer division result too large for a float:

product = 1      
list = []
i = 13
for num in range(i):
    list.append(num)

list = [x for x in list if x != 0]

for x in list:
    product *= x

final = product + 1
final2 = final/i

if float.is_integer(final2) == True:
    print("Prime")
else:
    print("Not prime")

As you can see, I used to divide the final by i. If the number was a prime one, it will return float.is_integer. But if the i variable was a big number, it will give the error.
Then I used the // method but I have no idea how to check if the the number is prime.
Here is the second scrpt, it’s the same but replacin the / for a //:

list = []
i = 17
for num in range(i):
    list.append(num)

list = [x for x in list if x != 0]

for x in list:
    product *= x

final = product + 1
final2 = final//i

if final2%1 == 0: #Here I have no idea of how to check if is a prime
    print("Prime")
else:
    print("Not prime")

I know this is not the best way to check if a number is prime.

Issue

I am trying to use a code to look for Wilson Primes for a bit of fun and to get me back into the swing of coding, however, I found that when I try to divide 172! +1 By 173 it gives me an Overflow error. Here is the code I am using:

import math
x = 2
while x < 1000:
    if math.factorial(x-1) + 1 % x == 0 and (math.factorial(x-1) + 1 / 5) % x == 0 :
        print(x)
    x += 1

Which when I run gives me:

5

13

OverflowError: integer division result too large for a float

I changed the code and found that the error occurs once the number 173 is used as x. Can anyone let me know why this is happening? I looked around but only found answers that said there was no limit to the size of numbers used in python. Thanks in advance

Solution

The problem is not the factorial, it is your calculation

(math.factorial(x-1) + 1 / 5) % x

Since x is an integer, the factorial returns an integer. However, 1 / 5 in Python 3 returns the float value 0.2. Adding an integer to a float returns a float, so Python tries to convert the factorial to a float.

However, Python 3’s integers can be any size, but that is not true of the floats. Float values are limited to the computer’s numeric processor, usually 8 bytes long, and have a maximum size. That size is exceeded, so Python returns an error.

If you mean to add one to the factorial, then divide that sum by 5, then take the modulus with x, you should add parentheses and use the integer division operator // rather then the float division operator /. I am not sure just what you are trying to do, so I can’t correct your code for you. But try the // operator.

Answered By – Rory Daulton

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Если у вас есть целое число и вы хотите, чтобы каждая цифра в списке, вы можете использовать:

>>> 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]

он преобразует int в строку, затем list будет принимать каждый символ строки и помещать ее в список. Наконец, map преобразует каждый элемент списка в int снова

Понравилась статья? Поделить с друзьями:
  • Как найти кадастровую стоимость нежилого помещения
  • Как найти открытый процесс
  • Как найти площадь квадрата зная корень
  • Как составить программу для занятий по английскому
  • Как исправить кадастровые ошибки по границам обязать