Overflow encountered in exp python ошибка

In this article we will discuss how to fix RuntimeWarning: overflow encountered in exp in Python.

This warning occurs while using the NumPy library’s exp() function upon using on a value that is too large. This function is used to calculate the exponential of all elements in the input array or an element (0-D Array of NumPy).

Example: Code to depict warning

Python3

import numpy as np

print(np.exp(789))

Output:

The output is infinity cause e^789 is a very large value 

This warning occurs because the maximum size of data that can be used in NumPy is float64 whose maximum range is 1.7976931348623157e+308. Upon taking logarithm its value becomes 709.782. For any larger value than this, the warning is generated.

Let us discuss ways to fix this.

Method 1: Using float128

The data type float64 can be changed to float128.

Example: Program to fix the warning

Python3

import numpy as np

x = 789

x = np.float128(x)

print(np.exp(x))

Output: 

 Using float128

For ndarray you can use the dtype parameter of the array method.

Example: Program to produce output without using dtype

Python3

import numpy as np

cc = np.array([789, 0.34, -1234.1])

print(np.exp(cc))

Output:

 without using dtype

Example: Fixed warning by using dtype

Python3

import numpy as np

cc = np.array([789, 0.34, -1234.1], dtype=np.float128)

print(np.exp(cc))

Output:

using dtype

Method 2: Using filterwarnings() 

Warning messages are typically issued in situations where it is useful to alert the user of some condition in a program, where that condition (normally) doesn’t warrant raising an exception and terminating the program. To deal with warnings there is a built-in module called warning. To read more about python warnings you can check out this article. 

The filterwarnings() function can be used to control the behavior of warnings in your programs. The warnings filter controls whether warnings are ignored, displayed, or turned into errors (raising an exception). This can be done using different actions:

  • “ignore” to never print matching warnings
  • “error” to turn matching warnings into exceptions
  • “once” to print only the first occurrence of matching warnings, regardless of location

Syntax:

warnings.filterwarnings(action, message=”, category=Warning, module=”, lineno=0, append=False)

Example: Fixing warning using filterwarnings()

Python3

import numpy as np

import warnings

warnings.filterwarnings('ignore')

x = 789

x = np.float128(x)

print(np.exp(x))

Output:

using filterwarnings()

Last Updated :
28 Nov, 2021

Like Article

Save Article

I’m trying to create a sigmoid function in Python, however, I get the following error:

RuntimeWarning: overflow encountered in exp

Here my code:

def sigmoid(self, value):

    a = np.exp(-value)
    return 1.0/ (1.0 + a)

I searched for previous answers, but they didn’t solve my problem.
The problem is on calculating the value of a.
I also tried using:

a = np.float128(np.exp(-value))

but I got the same error, and using:

a = np.float256(np.exp(-value))

I got the following error:

AttributeError: 'module' object has no attribute 'float256'

I thought that if I have an overflow I could return 0, and if I have an underflow I could return 1

  • Редакция Кодкампа

17 авг. 2022 г.
читать 1 мин


Одно предупреждение, с которым вы можете столкнуться в Python:

RuntimeWarning: overflow encountered in exp

Это предупреждение появляется, когда вы используете функцию выражения NumPy , но используете слишком большое значение для ее обработки.

Важно отметить, что это просто предупреждение и что NumPy все равно выполнит запрошенный вами расчет, но по умолчанию выдает предупреждение.

Когда вы сталкиваетесь с этим предупреждением, у вас есть два варианта:

1. Не обращайте внимания.

2. Полностью отключите предупреждение.

В следующем примере показано, как устранить это предупреждение на практике.

Как воспроизвести предупреждение

Предположим, мы выполняем следующий расчет в Python:

import numpy as np

#perform some calculation
print(1/(1+np.exp (1140)))

0.0

/srv/conda/envs/notebook/lib/python3.7/site-packages/ipykernel_launcher.py:3:
RuntimeWarning: overflow encountered in exp

Обратите внимание, что NumPy выполняет вычисления (результат равен 0,0), но по-прежнему печатает RuntimeWarning .

Это предупреждение выводится, потому что значение np.exp(1140) представляет e 1140 , что является массивным числом.

В основном мы просили NumPy выполнить следующие вычисления:

  • 1 / (1 + массивное число)

Это можно сократить до:

  • 1 / массивное число

Фактически это 0, поэтому NumPy вычислил результат равным 0.0 .

Как подавить предупреждение

Если мы хотим, мы можем использовать пакет warnings для подавления предупреждений следующим образом:

import numpy as np
import warnings

#suppress warnings
warnings. filterwarnings('ignore')

#perform some calculation
print(1/(1+np.exp (1140)))

0.0

Обратите внимание, что NumPy выполняет вычисления и не отображает RuntimeWarning.

Примечание.Как правило, предупреждения могут быть полезны для определения фрагментов кода, выполнение которых занимает много времени, поэтому будьте очень избирательны при принятии решения об отключении предупреждений.

Дополнительные ресурсы

В следующих руководствах объясняется, как исправить другие распространенные ошибки в Python:

Как исправить KeyError в Pandas
Как исправить: ValueError: невозможно преобразовать число с плавающей запятой NaN в целое число
Как исправить: ValueError: операнды не могли транслироваться вместе с фигурами

In this article we will discuss how to fix RuntimeWarning: overflow encountered in exp in Python.

This warning occurs while using the NumPy library’s exp() function upon using on a value that is too large. This function is used to calculate the exponential of all elements in the input array or an element (0-D Array of NumPy).

Example: Code to depict warning

Python3

import numpy as np

print(np.exp(789))

Output:

The output is infinity cause e^789 is a very large value 

This warning occurs because the maximum size of data that can be used in NumPy is float64 whose maximum range is 1.7976931348623157e+308. Upon taking logarithm its value becomes 709.782. For any larger value than this, the warning is generated.

Let us discuss ways to fix this.

Method 1: Using float128

The data type float64 can be changed to float128.

Example: Program to fix the warning

Python3

import numpy as np

x = 789

x = np.float128(x)

print(np.exp(x))

Output: 

For ndarray you can use the dtype parameter of the array method.

Example: Program to produce output without using dtype

Python3

import numpy as np

cc = np.array([789, 0.34, -1234.1])

print(np.exp(cc))

Output:

Example: Fixed warning by using dtype

Python3

import numpy as np

cc = np.array([789, 0.34, -1234.1], dtype=np.float128)

print(np.exp(cc))

Output:

Method 2: Using filterwarnings() 

Warning messages are typically issued in situations where it is useful to alert the user of some condition in a program, where that condition (normally) doesn’t warrant raising an exception and terminating the program. To deal with warnings there is a built-in module called warning. To read more about python warnings you can check out this article. 

The filterwarnings() function can be used to control the behavior of warnings in your programs. The warnings filter controls whether warnings are ignored, displayed, or turned into errors (raising an exception). This can be done using different actions:

  • “ignore” to never print matching warnings
  • “error” to turn matching warnings into exceptions
  • “once” to print only the first occurrence of matching warnings, regardless of location

Syntax:

warnings.filterwarnings(action, message=”, category=Warning, module=”, lineno=0, append=False)

Example: Fixing warning using filterwarnings()

Python3

import numpy as np

import warnings

warnings.filterwarnings('ignore')

x = 789

x = np.float128(x)

print(np.exp(x))

Output:


One warning you may encounter in Python is:

RuntimeWarning: overflow encountered in exp

This warning occurs when you use the NumPy exp function, but use a value that is too large for it to handle.

It’s important to note that this is simply a warning and that NumPy will still carry out the calculation you requested, but it provides the warning by default.

When you encounter this warning, you have two options:

1. Ignore it.

2. Suppress the warning entirely.

The following example shows how to address this warning in practice.

How to Reproduce the Warning

Suppose we perform the following calculation in Python:

import numpy as np

#perform some calculation
print(1/(1+np.exp(1140)))

0.0

/srv/conda/envs/notebook/lib/python3.7/site-packages/ipykernel_launcher.py:3:
RuntimeWarning: overflow encountered in exp

Notice that NumPy performs the calculation (the result is 0.0) but it still prints the RuntimeWarning.

This warning is printed because the value np.exp(1140) represents e1140, which is a massive number.

We basically requested NumPy to perform the following calculation:

  • 1 / (1 + massive number)

This can be reduced to:

  • 1 / massive number

This is effectively 0, which is why NumPy calculated the result to be 0.0.

How to Suppress the Warning

If we’d like, we can use the warnings package to suppress warnings as follows:

import numpy as np
import warnings

#suppress warnings
warnings.filterwarnings('ignore')

#perform some calculation
print(1/(1+np.exp(1140)))

0.0

Notice that NumPy performs the calculation and does not display a RuntimeWarning.

Note: In general, warnings can be helpful for identifying bits of code that take a long time to run so be highly selective when deciding to suppress warnings.

Additional Resources

The following tutorials explain how to fix other common errors in Python:

How to Fix KeyError in Pandas
How to Fix: ValueError: cannot convert float NaN to integer
How to Fix: ValueError: operands could not be broadcast together with shapes

Возможно, вам также будет интересно:

  • Over ошибка на весах
  • Over voltage ошибка частотника
  • Over current ошибка частотника
  • Over 7s brusko ошибка
  • Outriders ошибка подключения к серверу

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

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