- Что означает ошибка OverflowError: math range error
- Что делать с ошибкой OverflowError: math range error
- OverflowError Exception in Python
- Example 1
- Example 2 — Handling OverflowError in Python
- Subscribe to Pylenin
- Python OverflowError
- How does Python OverflowError work?
- Examples to Implement Python OverflowError
- Example #1
- Example #2
- Example #3
- Example #4
- Conclusion
- Recommended Articles
Что означает ошибка OverflowError: math range error
Ситуация: для научной диссертации по логарифмам мы пишем модуль, который будет возводить в разные степени число Эйлера — число e, которое примерно равно 2,71828. Для этого мы подключаем модуль math, где есть нужная нам команда — math.exp(), которая возводит это число в указанную степень.
Нам нужно выяснить различные значения числа в степени от 1 до 1000, чтобы потом построить график, поэтому пишем такой простой модуль:
# импортируем математический модуль import math # список с результатами results = [] # перебираем числа от 1 до 1000 for i in range(1000): # добавляем результат в список results.append(math.exp(i)) # и выводим его на экран print(results[i-1])
Но при запуске кода компьютер выдаёт ошибку:
❌ OverflowError: math range error
Что это значит: компьютер во время расчётов вылез за допустимые границы переменной — ему нужно записать в неё большее значение, чем то, на которое она рассчитана.
Когда встречается: во время математических расчётов, которые приводят к переполнению выделенной для переменной памяти. При этом общий размер оперативной памяти вообще не важен — имеет значение только то, сколько байт компьютер выделил для хранения нашего конкретного значения. Если у вас, например, 32 Гб оперативной памяти, это не поможет решить проблему.
Что делать с ошибкой OverflowError: math range error
Так как это ошибка переполнения, то самая частая причина этой ошибки — попросить компьютер посчитать что-то слишком большое.
Чтобы исправить ошибку OverflowError: math range error, есть два пути — использовать разные трюки или специальные библиотеки для вычисления больших чисел или уменьшить сами вычисления. Про первый путь поговорим в отдельной статье, а пока сделаем проще: уменьшим диапазон с 1000 до 100 чисел — этого тоже хватит для построения графика:
# импортируем математический модуль import math # список с результатами results = [] # перебираем числа от 1 до 100 for i in range(100): # добавляем результат в список results.append(math.exp(i)) # и выводим его на экран print(results[i-1])
В «Яндекс Практикуме» можно стать разработчиком, тестировщиком, аналитиком и менеджером цифровых продуктов. Первая часть обучения всегда бесплатная, чтобы попробовать и найти то, что вам по душе. Дальше — программы трудоустройства.
При вставке все будут видеть, откуда скопирован текст
Сохраняем тему и добавляем переключатель
Ей уже 60 лет, но она до сих пор работает быстро
Никакой магии, только JavaScript.
Суперпростой способ создать бота, не зная программирования.
OverflowError Exception in Python
Handle Overflow Error exception in Python using the try-except block.
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 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", ")
Output
5.0 25.0 15625.0 5.960464477539062e+16 7.52316384526264e+83 Overflow error happened (34, 'Result too large'),
Subscribe to Pylenin
Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
Python OverflowError
In Python, OverflowError occurs when any operations like arithmetic operations or any other variable storing any value above its limit then there occurs an overflow of values that will exceed it’s specified or already defined limit. In general, in all programming languages, this overflow error means the same. In Python also this error occurs when an arithmetic operation result is stored in any variable where the result value is larger than any given data type like float, int, etc exceeds the limit or value of current Python runtime values. Therefore when these values are larger than the declared data type values will result to raise memory errors.
How does Python OverflowError work?
Working of Overflow Error in Python:
In this article, we will see when and how this overflow error occurs in any Python program. An overflow error, in general, is as its name suggests which means overflow itself defines an extra part, therefore in Python also this occurs when an obtained value or result is larger than the declared operation or data type in the program then this throws an overflow error indicating the value is exceeding the given or declared limit value.
Examples to Implement Python OverflowError
Now let us see simple and general examples below:
Example #1
print("Simple program for showing overflow error") print("\n") import math print("The exponential value is") print(math.exp(1000))
Explanation: In the above program, we can see that we are declaring math module and using to calculate exponential value such as exp(1000) which means e^x here x value is 1000 and e value is 2.7 where when are trying to calculate this it will give value as a result which is double and it cannot print the result, therefore, it gives an overflow error as seen in the above program which says it is out of range because the x value is 1000 which when results give the value which is out of range or double to store the value and print it.
Example #2
Now we will see a program that will give an error due to data type value storage which exceeds the range. In the above program, we saw the arithmetic operation. Now let us demonstrate this value exceeds in data type values in the below example:
import time currtime = [tm for tm in time.localtime()] print("Print the current data and time") print(currtime) print("\n") time2 = (2**73) print("The invlaid time is as follows:") print(time2) print("\n") currtime[3] = time2 time3 = time.asctime(currtime) print(time3)
Explanation: In the above program, we are printing the current time using the time module, when we are printing cure time in the program we are printing current time using time.local time() function which results in the output with [year, month, day, minutes, seconds… ] and then we are trying to print the value by changing the hours to a larger value the limit it can store. Therefore when we are trying to print this value it will throw an error saying Python int is too large to convert to C long. Where it means it cannot store such big value and convert it to the long data type. This output gives overflow error because the time3 uses plain integer object and therefore it cannot take objects of arbitrary length. These errors can be handled by using exception handling. In the below section we will see about this exception handling. In the above programs, we saw the Overflow error that occurred when the current value exceeds the limit value. So to handle this we have to raise overflowError exception. This exception in hierarchal found in order is BaseException, Exception, ArithmeticError, and then comes OverflowError. Now let us see the above programs on how to resolve this problem.
Example #3
Now let us see how we can handle the above math out of range as overflow error by using try and except exception handling in the below program. Code:
print("Simple program for showing overflow error") print("\n") import math try: print("The exponential value is") print(math.exp(1000)) except OverflowError as oe: print("After overflow", oe)
Explanation: So we can see in the above screenshot where we are handling the OverflowError by using try and except block and it will print the message when it throws this exception. We can see it in the above result output how the exception is handled.
Example #4
Let us see the solution of another program in the above section by using this exception handling concept. Let us demonstrate it below:
import time try: currtime = [tm for tm in time.localtime()] print("Print the current data and time") print(currtime) print("\n") time2 = (2**73) print("The invlaid time is as follows:") print(time2) print("\n") currtime[3] = time2 print(time.asctime(currtime)) except OverflowError as oe: print("After the Overflow error", oe)
Explanation: In the above program, we can see that again we handled the OverflowError by using try and except blocks or exception handling as we did it in the above program.
Conclusion
In this article, we conclude that an overflow error is an error that occurs when the current runtime value obtained by the Python program exceeds the limit value. In this article, we saw this error occurs when we use arithmetic operations in the program and the result exceeds the limit range value. We also saw this error occurs when we are trying to convert from one data type to another when the value is larger than the given data type storage range. Lastly, we saw how to handle this error using exception handling using try and except block.
Recommended Articles
This is a guide to Python OverflowError. Here we discuss an introduction to Python OverflowError, how does it work with programming examples. You can also go through our other related articles to learn more –