Int too large to convert to float как исправить

Есть задание в котором следует исследовать ряд на сходимость Условие окончания цикла вычисления суммы принять в виде: | un | G где Е - малая величина для прерывания цикла

Есть задание в котором следует исследовать ряд на сходимость
введите сюда описание изображения

Условие окончания цикла вычисления суммы принять в виде:
| un | <E або | un | > G где Е — малая величина для прерывания цикла вычисления суммы схождения ряда (е = 10-5 … 10-20); G — величина для прерывания цикла вычисления суммы расхождения ряда (g = 102 …
105).

и у меня есть некий скрипт:

def task_series12():
    """check the series (variant 12) for convergence"""
    n = 1
    s = u = 2
    e = 1e-10  # g = 1e+5
    while abs(u) > e:  # abs(u)>g
        print(u)
        n += 1
        if n ** math.sqrt(n) == 0:
            break
        u = (math.factorial(n) * math.exp(n)) / (n ** math.sqrt(n))
        s += u
    else:
        print("Series converge to: ", s)  # "Maximum sum is:"
        return True
    print("Division by zero!")
    return False

но как итог выбивает ошибку OverflowError: int too large to convert to float

Как это исправить?

задан 2 дек 2020 в 19:18

Alex Rey's user avatar

Вызов math.factorial(n), n > 170 порождает числа которые не могут быть переведены во float.

Чтобы это исправить, выразите член ряда a(n + 1) через a(n). Вычисляйте их в цикле друг через друга. Так вы продвинетесь дальше.

Но далеко вы не уйдёте. Чтобы понять почему, печатайте значения a(n) и вспоминайте условие сходимости ряда.

ответ дан 2 дек 2020 в 19:30

Stanislav Volodarskiy's user avatar

Зря вы игнорировали часть задания «G — величина для прерывания цикла вычисления суммы расхождения ряда». Вам надо проверять и эту часть. Ряд может как сходиться, так и расходиться.

Если вам нужно в цикле проверять несколько условий выхода, то лучше это делать так:

e = 1e-10
g = 1e+5
while True:
    if abs(u) < e:
        print('Ряд сошёлся')
        break
    if abs(u) > g:
        print('Ряд разошёлся')
        break
    # остальное тело цикла

ответ дан 2 дек 2020 в 19:33

CrazyElf's user avatar

CrazyElfCrazyElf

62.4k5 золотых знаков19 серебряных знаков47 бронзовых знаков

I’d like to calculate (⌊2^(1918)*π⌋+124476) in python but I get this error when I do it using the following code:

b = math.floor((2**1918) * math.pi) + 124476
print(b)

OverflowError: int too large to convert to float

How can you get this to work? In the end I just like to have it all as hexadecimal (if that helps with answering my question) but I was actually only trying to get it as an integer first :)

asked Jun 12, 2019 at 15:50

3

The right solution really depends on how precise the results are required. Since 2^1918 already is too large for both standard integer and floating point containers, it is not possible to get away with direct calculations without loosing all the precision below ~ 10^300.

In order to compute the desired result, you should use arbitrary-precision calculation techniques. You can implement the algorithms yourself or use one of the available libraries.

Assuming you are looking for an integer part of your expression, it will take about 600 decimal places to store the results precisely. Here is how you can get it using mpmath:

from mpmath import mp
mp.dps = 600
print(mp.floor(mp.power(2, 1918)*mp.pi + 124476))

74590163000744215664571428206261183464882552592869067139382222056552715349763159120841569799756029042920968184704590129494078052978962320087944021101746026347535981717869532122259590055984951049094749636380324830154777203301864744802934173941573749720376124683717094961945258961821638084501989870923589746845121992752663157772293235786930128078740743810989039879507242078364008020576647135087519356182872146031915081433053440716531771499444683048837650335204793844725968402892045220358076481772902929784589843471786500160230209071224266538164123696273477863853813807997663357545.0

Next, all you have to do is to convert it to hex representation (or extract hex from its internal binary form), which is a matter for another subject :)

answered Jun 12, 2019 at 16:26

M0nZDeRR's user avatar

M0nZDeRRM0nZDeRR

2163 silver badges7 bronze badges

11

The basic problem is what the message says. Python integers can be arbitrarily large, larger even than the range of a float. 2**1918 in decimal contains 578 significant digits and is way bigger than the biggest float your IEEE754 hardware can represent. So the call just fails.

You could try looking at the mpmath module. It is designed for floating point arithmetic outside the bounds of what ordinary hardware can handle.

answered Jun 12, 2019 at 16:18

BoarGules's user avatar

BoarGulesBoarGules

16.1k2 gold badges29 silver badges43 bronze badges

0

I think the problem can be solved without resorting to high-precision arithmetic. floor(n.something + m) where m and n are integers is equal to floor(n.something) + m. So in this case you are looking for floor(2**1918 * pi) plus an integer (namely 124476). floor(2**whatever * pi) is just the first whatever + 2 bits of pi. So just look up the first 1920 bits of pi, add the bits for 124476, and output as hex digits.

A spigot algorithm can generate digits of pi without using arbitrary precision. A quick web search seems to find some Python implementations for generating digits in base 10. I didn’t see anything about base 2, but Plouffe’s formula generates base 16 digits if I am not mistaken.

answered Jun 12, 2019 at 18:02

Robert Dodier's user avatar

Robert DodierRobert Dodier

16.4k2 gold badges30 silver badges46 bronze badges

2

The problem is that (2**1918) * math.pi attempts to convert the integer to 64-bit floating point precision, which is insufficiently large. You can convert math.pi to a fraction to use arbitrary precision.

>>> math.floor((2**1918) * fractions.Fraction(math.pi) + 124476)
74590163000744212756918704280961225881025315246628098737524697383138220762542289800871336766911957454080350508173317171375032226685669280397906783245438534131599390699781017605377332298669863169044574050694427882869191541933796848577277592163846082732344724959222075452985644173036076895843129191378853006780204194590286508603564336292806628948212533561286572102730834409985441874735976583720122784469168008083076285020654725577288682595262788418426186598550864392013191287665258445673204426746083965447956681216069719524525240073122409298640817341016286940008045020172328756796

Note that arbitrary precision applies to the calculation; math.pi is defined only with 64-bit floating point precision. Use an external library, such as mpmath, if you need the exact value.

To convert this to a hexadecimal string, use hex or a string format:

>>> hex(math.floor((2**1918) * fractions.Fraction(math.pi) + 124476))
'0xc90fdaa22168c0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001e63c'
>>> '%x' % math.floor((2**1918) * fractions.Fraction(math.pi) + 124476)
'c90fdaa22168c0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001e63c'
>>> f'{math.floor((2**1918) * fractions.Fraction(math.pi) + 124476):X}'
'C90FDAA22168C0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001E63C'

For string formats, x provides lower-case hex whereas X provides upper-case case.

answered Jun 12, 2019 at 16:26

MisterMiyagi's user avatar

MisterMiyagiMisterMiyagi

41.5k10 gold badges98 silver badges110 bronze badges

Уведомления

  • Начало
  • » Python для новичков
  • » Ошибка: OverflowError: long int too large to convert to float

#1 Июнь 29, 2015 11:51:45

Ошибка: OverflowError: long int too large to convert to float

Привет всем!
Есть код:

# -*- coding:cp1251 -*-
import math
eps = 0.001
x = 5.0
rez = x
znam = 2
shag = 2
while True :
    n = znam
    el = 1 - x**n / math.factorial(znam)
    rezNew = rez + el
    if abs( rezNew - rez ) < eps :
        rez = rezNew
        break
    rez = rezNew
    znam += shag
print math.cos(x), rez

Выдает ошибку:
Traceback (most recent call last):
File “Dpython/zad4/z4.2.4.py”, line 13, in <module>
el = 1 — x**n / math.factorial(znam)
OverflowError: long int too large to convert to float

В чем проблема?

Отредактировано vihard (Июнь 29, 2015 11:53:11)

Офлайн

  • Пожаловаться

#2 Июнь 29, 2015 12:07:41

Ошибка: OverflowError: long int too large to convert to float

гуглится за семь секунд
например

Офлайн

  • Пожаловаться

#3 Июнь 29, 2015 12:14:43

Ошибка: OverflowError: long int too large to convert to float

Спасибо, я в курсе, но хотелось бы объяснения на родном языке)

Офлайн

  • Пожаловаться

#4 Июнь 29, 2015 12:31:20

Ошибка: OverflowError: long int too large to convert to float

во float помещаются числа в диапазоне

sys.float_info(max=1.7976931348623157e+308, max_exp=1024, max_10_exp=308, min=2.2250738585072014e-308, min_exp=-1021, min_10_exp=-307, dig=15, mant_dig=53, epsilon=2.220446049250313e-16, radix=2, rounds=1)

от 2.2250738585072014e-308 до 1.7976931348623157e+308
факториал от 172

In [3]: len(str(math.factorial(172)))
Out[3]: 312

в него уже не помещается

Вот здесь один из первых отарков съел лаборанта. Это был такой умный отарк, что понимал даже теорию относительности. Он разговаривал с лаборантом, а потом бросился на него и загрыз…

Отредактировано PooH (Июнь 29, 2015 12:31:53)

Офлайн

  • Пожаловаться

#5 Июнь 29, 2015 12:58:16

Ошибка: OverflowError: long int too large to convert to float

PooH
во float помещаются числа в диапазоне

Спасибо, PooH, но как эта проблема решается, и конкретно в моем случае? Как я понял, нужно использовать некий метод Decimal? Но каковы правила его использования? Я пробовал по образцу, все равно выдает ошибку.

Офлайн

  • Пожаловаться

#6 Июнь 29, 2015 12:59:55

Ошибка: OverflowError: long int too large to convert to float

vihard
В чем проблема?

Скорее всего, выбран неверный алгоритм.

vihard

el = 1 - x**n / math.factorial(znam)

Деление на факториал вызывает подозрения.

Офлайн

  • Пожаловаться

#7 Июнь 29, 2015 13:03:11

Ошибка: OverflowError: long int too large to convert to float

py.user.next

Ошибка возникает даже если в знаменателе поставить просто переменную znam

Офлайн

  • Пожаловаться

#8 Июнь 29, 2015 13:30:30

Ошибка: OverflowError: long int too large to convert to float

это часом не косинус через ряд Тейлора должно считать?

Вот здесь один из первых отарков съел лаборанта. Это был такой умный отарк, что понимал даже теорию относительности. Он разговаривал с лаборантом, а потом бросился на него и загрыз…

Офлайн

  • Пожаловаться

#9 Июнь 29, 2015 13:31:35

Ошибка: OverflowError: long int too large to convert to float

vihard
Ошибка возникает даже если в знаменателе поставить просто переменную znam

Задание напиши. Может быть неправильным не только алгоритм, но и код реализации неправильного алгоритма.

Офлайн

  • Пожаловаться

#10 Июнь 29, 2015 14:00:45

Ошибка: OverflowError: long int too large to convert to float

py.user.next

Вычислить с точностью 0.001:

Офлайн

  • Пожаловаться

  • Начало
  • » Python для новичков
  • » Ошибка: OverflowError: long int too large to convert to float

Python float() function is used to return a floating-point number from a number or a string representation of a numeric value.

Python float() Function syntax

Syntax:  float(x)

Parameter x: x is optional & can be:

  • any number or number in form of string, ex,: “10.5”
  • inf or infinity, NaN (any cases)

Return: Float Value

Python float() Function example

Python3

num = float(10)

print(num)

Output:

10.0

Values that the Python float() method can return depending upon the argument passed

  • If an argument is passed, then the equivalent floating-point number is returned.
  • If no argument is passed then the method returns 0.0.
  • If any string is passed that is not a decimal point number or does not match any cases mentioned above then an error will be raised.
  • If a number is passed outside the range of Python float then OverflowError is generated.

Python float() example

Example 1: How Python float() works

Python3

print(float(21.89))

print(float(8))

print(float("23"))

print(float("-16.54"))

print(float("     -24.45   n"))

print(float("InF"))

print(float("InFiNiTy"))

print(float("nan"))

print(float("NaN"))

print(float("Geeks"))

Output: 

21.89
8.0
23.0
-16.54
-24.45
inf
inf
nan
nan

All lines are executed properly but the last one will return an error: 

Traceback (most recent call last):
  File "/home/21499f1e9ca207f0052f13d64cb6be31.py", line 25, in 
    print(float("Geeks"))
ValueError: could not convert string to float: 'Geeks'

Example 2: float() for infinity and Nan

Python3

print(float("InF"))

print(float("InFiNiTy"))

print(float("nan"))

print(float("NaN"))

Output:

inf
inf
nan
nan

Example 3: Converting an Integer to a Float in Python

Python3

number = 90

result = float(number)

print(result)

Output:

90.0

Example 4: Converting a String to a Float in Python

Python3

string = "90"

result = float(string)

print(result)

Output:

90.0

Example 5: Python float() exception

float() will raise ValueError if passed parameter is not a numeric value.

Python3

number = "geeks"

try:

    print(float(number))

except ValueError as e:

    print(e)

Output:

could not convert string to float: 'geeks'

Example 6: Python float() OverflowError

float() will raise OverflowError if passed parameter is too large (ex.: 10**309)

Python3

Output:

Traceback (most recent call last):
  File "/home/1eb6a2abffa536ccb1cae660db04a162.py", line 1, in <module>
    print(float(10**309))
OverflowError: int too large to convert to float

Comments

@haik

When I try to decrypt the ciphertext by using priv.decrypt(n1_r1_enc) and n1_r1_enc is the sum of n1 and r1, it raised the following error.

File «/usr/local/lib/python3.6/site-packages/phe/paillier.py», line 287, in decrypt
return encoded.decode()
File «/usr/local/lib/python3.6/site-packages/phe/encoding.py», line 220, in decode
return mantissa * pow(self.BASE, self.exponent)

It is weird because it can decrypt correctly when n1 and r1 are the following values.

r1: 462
n1: 2.954413649165506
n1+r1: 464.95441364916553

The error occurred when n1 and r1 are the following values:

r1: 593
n1: 0.1641340916202469

or:

r1: 445
n1: 0.16413409062205825

I really have no idea about what is going wrong.

gusmith

pushed a commit
that referenced
this issue

Jun 27, 2018

@gusmith

I tried to repeat the issue, but I was not able to.
Could you specify:

  • how you created your key pair
  • how you encrypted the numbers
  • how you summed the numbers together
  • if gmpy2 is installed?

See the branch issue-62 d7e6e58 where I added a test which repeats what you have described in this issue, but I did not get any exceptions.

@nbgl
nbgl

mentioned this issue

Dec 19, 2018

@nbgl

Here’s how I can reproduce it:

>>> pub, priv = phe.generate_paillier_keypair()
>>> a = pub.encrypt(445)
>>> b = pub.encrypt(0.16413409062205825) + pub.encrypt(2 ** -965)  # Force big exponent.
>>> priv.decrypt(a + b)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Users/jakub/Repositories/python-paillier/phe/paillier.py", line 290, in decrypt
    return encoded.decode()
  File "/Users/jakub/Repositories/python-paillier/phe/encoding.py", line 220, in decode
    return mantissa * pow(self.BASE, self.exponent)
OverflowError: int too large to convert to float

This issue is fixed with #73.

nbgl

pushed a commit
that referenced
this issue

Dec 19, 2018

Понравилась статья? Поделить с друзьями:

Читайте также:

  • Int object is not callable питон как исправить
  • Intel raid 1 volume как исправить
  • Int error python
  • Intel r visual fortran run time error
  • Int cannot be dereferenced java ошибка

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

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