Factorials get large real fast:
>>> math.factorial(170)
7257415615307998967396728211129263114716991681296451376543577798900561843401706157852350749242617459511490991237838520776666022565442753025328900773207510902400430280058295603966612599658257104398558294257568966313439612262571094946806711205568880457193340212661452800000000000000000000000000000000000000000L
Note the L; the factorial of 170 is still convertable to a float:
>>> float(math.factorial(170))
7.257415615307999e+306
but the next factorial is too large:
>>> float(math.factorial(171))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
OverflowError: long int too large to convert to float
You could use the decimal module; calculations will be slower, but the Decimal() class can handle factorials this size:
>>> from decimal import Decimal
>>> Decimal(math.factorial(171))
Decimal('1241018070217667823424840524103103992616605577501693185388951803611996075221691752992751978120487585576464959501670387052809889858690710767331242032218484364310473577889968548278290754541561964852153468318044293239598173696899657235903947616152278558180061176365108428800000000000000000000000000000000000000000')
You’ll have to use Decimal() values throughout:
from decimal import *
with localcontext() as ctx:
ctx.prec = 32 # desired precision
p = ctx.power(3, idx)
depart = ctx.exp(-3) * p
depart /= math.factorial(idx)
Уведомления
- Начало
- » 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 “D
python/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
Exception in thread Thread-1:
Traceback (most recent call last):
File "c:python38libthreading.py", line 932, in _bootstrap_inner
self.run()
File "c:python38libthreading.py", line 870, in run
self._target(*self._args, **self._kwargs)
File "C:UsersDellOneDriveDesktopNew Foldermailersend_mail.py", line 42, in <lambda>
target=lambda: self.make_mail_objects(spreadsheet_path)
File "C:UsersDellOneDriveDesktopNew Foldermailersend_mail.py", line 66, in make_mail_objects
self.mail_queue.put(self.get_mail_object_from_row(row))
File "C:UsersDellOneDriveDesktopNew Foldermailersend_mail.py", line 115, in get_mail_object_from_row
msg.add_message(
File "C:UsersDellOneDriveDesktopNew Foldermailerprepare_message.py", line 156, in add_message
template.render(context)
File "C:UsersDellOneDriveDesktopNew foldervenvlibsite-packagesdocxtpl__init__.py", line 310, in render
xml_src = self.build_xml(context, jinja_env)
File "C:UsersDellOneDriveDesktopNew foldervenvlibsite-packagesdocxtpl__init__.py", line 269, in build_xml
xml = self.render_xml(xml, context, jinja_env)
File "C:UsersDellOneDriveDesktopNew foldervenvlibsite-packagesdocxtpl__init__.py", line 218, in render_xml
dst_xml = template.render(context)
File "C:UsersDellOneDriveDesktopNew foldervenvlibsite-packagesjinja2environment.py", line 1090, in render
self.environment.handle_exception()
File "C:UsersDellOneDriveDesktopNew foldervenvlibsite-packagesjinja2environment.py", line 832, in handle_exception
reraise(*rewrite_traceback_stack(source=source))
File "C:UsersDellOneDriveDesktopNew foldervenvlibsite-packagesjinja2_compat.py", line 28, in reraise
raise value.with_traceback(tb)
File "<template>", line 1, in top-level template code
File "C:UsersDellOneDriveDesktopNew foldervenvlibsite-packagesdocxtpl__init__.py", line 821, in __str__
return self._insert_image()
File "C:UsersDellOneDriveDesktopNew foldervenvlibsite-packagesdocxtpl__init__.py", line 809, in _insert_image
pic = self.tpl.docx._part.new_pic_inline(
File "C:UsersDellOneDriveDesktopNew foldervenvlibsite-packagesdocxpartsstory.py", line 57, in new_pic_inline
cx, cy = image.scaled_dimensions(width, height)
File "C:UsersDellOneDriveDesktopNew foldervenvlibsite-packagesdocximageimage.py", line 158, in scaled_dimensions
scaling_factor = float(width) / float(self.width)
OverflowError: int too large to convert to float
Image:

width:
Mm(5)
Факториалы становятся большими реальными:
>>> math.factorial(170)
7257415615307998967396728211129263114716991681296451376543577798900561843401706157852350749242617459511490991237838520776666022565442753025328900773207510902400430280058295603966612599658257104398558294257568966313439612262571094946806711205568880457193340212661452800000000000000000000000000000000000000000L
Обратите внимание на L; факториал 170 по-прежнему можно преобразовать в float:
>>> float(math.factorial(170))
7.257415615307999e+306
но следующий факториал слишком велик:
>>> float(math.factorial(171))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
OverflowError: long int too large to convert to float
Вы можете использовать модуль decimal; вычисления будут медленнее, но класс Decimal() может обрабатывать факториалы такого размера:
>>> from decimal import Decimal
>>> Decimal(math.factorial(171))
Decimal('1241018070217667823424840524103103992616605577501693185388951803611996075221691752992751978120487585576464959501670387052809889858690710767331242032218484364310473577889968548278290754541561964852153468318044293239598173696899657235903947616152278558180061176365108428800000000000000000000000000000000000000000')
Вам нужно использовать значения Decimal():
from decimal import *
with localcontext() as ctx:
ctx.prec = 32 # desired precision
p = ctx.power(3, idx)
depart = ctx.exp(-3) * p
depart /= math.factorial(idx)
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