Python интеграл ошибок

scipy.stats.norm.cdf(x)

Дает интеграл плотности распределения. По сути оно и есть функция Лапласа. Это интеграл от минус бесконечности до х. Оно же зовется cdf.
введите сюда описание изображения

В таблицах используется нормированная функция Лапласа, которая (как уже отмечалось) равна обычной функции минус 0,5. Она представляет интеграл от 0 до х.
введите сюда описание изображения

Вот вывод из книги Письменный Д.Т. Конспект лекций по теории вероятностей, математической статистике и случайным процессам:
введите сюда описание изображения

Отсюда и понятно, почему нужно вычитать 0,5. Ведь интеграл всей плотности вероятности равен единице. А он симметричен. И именно отрицательная часть равна 0,5.

Так же вы можете использовать erf. Она связана с cdf (см статью на википедии).

А вот этот ответ дал мне возможность ускорить cdf еще сильнее чем scipy.

В своем проекте я вешаю еще jit компиляцию. И это выходит в два раза быстрее чем cdf.(Normal(0,1),x) на Julia. В итоге ускорение в сравнении с scipy было в 10 раз.

Моя реализация представлена ниже. Но к сожалению у неё отсутствует проверка входных данных, так что обеспечьте её сами.

@nb.njit(cache=True)
def cdf(x):
    """
    Расчет функции Лапласа.

    Внимание! Отключена проверка по границам
    """

    x = x / 1.414213562
    a1 = 0.254829592
    a2 = -0.284496736
    a3 = 1.421413741
    a4 = -1.453152027
    a5 = 1.061405429
    p = 0.3275911
    s = np.sign(x)
    t = 1 / (1 + s * p * x)
    b = np.exp(-x * x)
    y = (s * s + s) / 2 - 
        s * (((((a5 * t + a4) * t) + a3) * t + a2) * t + a1) * t * b / 2
    return y

Подборка по базе: Итоговый тест по главе 1. Тепловые явления. (Часть 1)Вариант 2 к, Эконометрика «Синергия» МАКСИМУМ.pdf, Работа со статьей учебника.docx, РЕФЕРАТ Исмурзинов Максат фт-300015.docx, Анализ учебников с 1 по 4 класс по русскому языку и основные пон, мартынова Макс.docx, Учет и отчетность в бюджетных организациях_текст учебника.pdf, Словарь к учебнику Rainbow English 3 класс.docx, анализ учебника.docx, Рецензия на учебник.docx


благодаря чему каждый следующий рекурсивный вызов этой функции пользу- ется своим набором локальных переменных и за счёт этого работает корректно.
Оборотной стороной этого довольно простого по структуре механизма является то, что на каждый рекурсивный вызов требуется некоторое количество опера- тивной памяти компьютера, и при чрезмерно большой глубине рекурсии может наступить переполнение стека вызовов.
Вопрос о желательности использования рекурсивных функций в программи- ровании неоднозначен: с одной стороны, рекурсивная форма может быть струк- турно проще и нагляднее, в особенности, когда сам реализуемый алгоритм, по сути, рекурсивен. Кроме того, в некоторых декларативных или чисто функци- ональных языках (таких, как Пролог или Haskell) просто нет синтаксических средств для организации циклов, и рекурсия в них — единственный доступный механизм организации повторяющихся вычислений. С другой стороны, обычно рекомендуется избегать рекурсивных программ, которые приводят (или в некото- рых условиях могут приводить) к слишком большой глубине рекурсии. Так, ши- роко распространённый в учебной литературе пример рекурсивного вычисления факториала является, скорее, примером того, как не надо применять рекурсию,
так как приводит к достаточно большой глубине рекурсии и имеет очевидную реализацию в виде обычного циклического алгоритма.
4.6
Примеры решения заданий
Пример задачи 12 Напишите функцию, вычисляющую значения экспо- ненты по рекуррентной формуле e x
= 1 + x +
x
2 2!
+
x
3 3!
+ · · · =
P

n=0
x n
n!
. Ре- ализуйте контроль точности вычислений с помощью дополнительного параметра ε со значением по умолчанию (следует остановить вычисле- ния, когда очередное приближение будет отличаться от предыдущего менее, чем на 10

10
).
Реализуйте вызов функции различными способами:

4.6. Примеры решения заданий
107
• с одним позиционным параметром (при этом будет использовано значение по умолчанию);
• с двумя позиционными параметрами (значение точности будет пе- редано как второй аргумент);
• передав значение как именованный параметр.
Решение задачи 12
d e
f
E X P O N E N T A (x , eps =10**( -10)):
ex = 1 # будущий результат dx = x # приращение i = 2
#
номер приращения w
h i
l e
a b
s
( dx ) > eps :
ex = ex + dx dx = dx * x / i i = i + 1
r e
t u
r n
ex
#
Основная программа
A =
f l
o a
t
(
i n
p u
t
( ’Введите показатель экспоненты: ’ ))
p r
i n
t
( E X P O N E N T A ( A ))
p r
i n
t
( E X P O N E N T A (A , 10**( -4)))
p r
i n
t
( E X P O N E N T A ( x = A )
Пример задачи 13 Сделайте из функции процедуру (вместо того, что- бы вернуть результат с помощью оператора return, выведите его внут- ри функции с помощью функции print).
Решение задачи 13
d e
f
E X P O N E N T A (x , eps =10**( -10)):
ex = 1 # будущий результат dx = x # приращение i = 2
#
номер приращения w
h i
l e
a b
s
( dx ) > eps :
ex = ex + dx dx = dx * x / i i = i + 1
p r
i n
t
( ex )
#
Основная программа
A =
f l
o a
t
(
i n
p u
t
( ’Введите показатель экспоненты: ’ ))
E X P O N E N T A ( A )

108
Глава 4. Функции
4.7
Задания на функции
Задание 11 Выполнять одно задание в зависимости от номера в спис- ке:
(n-1)%10+1
, где n — номер в списке. Напишите функцию, вычисляю- щую значения одной из следующих специальных функций по рекуррент- ной формуле. Реализуйте контроль точности вычислений с помощью до- полнительного параметра ε со значением по умолчанию (следует оста- новить вычисления, когда очередное приближение будет отличаться от предыдущего менее, чем на 10

10
). Реализуйте вызов функции различны- ми способами:
• с одним позиционным параметром (при этом будет использовано значение по умолчанию);
• с двумя позиционными параметрами (значение точности будет пе- редано как второй аргумент);
• передав значение как именованный параметр.
Сделайте из функции процедуру (вместо того, чтобы вернуть резуль- тат с помощью оператора return, выведите его внутри функции с по- мощью функции print).
1. Косинус cos(x) = 1 −
x
2 2!
+
x
4 4!
− · · · =
P

n=0
(−1)
n x
2n
(2n)!
. Формула хорошо ра- ботает для −2π 6 x 6 2π, поскольку получена разложением в ряд Тейлора возле ноля. Для прочих значений x следует воспользоваться свойствами периодичности косинуса: cos(x) = cos(2 + 2πn), где n есть любое целое число, тогда cos(x) = cos(x%(2*math.pi)). Для проверки использовать функцию math.cos(x).
2. Синус sin(x) = x −
x
3 3!
+
x
5 5!
+ · · · =
P

n=0
(−1)
n x
2n+1
(2n+1)!
. Формула хорошо ра- ботает для −2π 6 x 6 2π, поскольку получена разложением в ряд Тейлора возле ноля. Для прочих значений x следует воспользоваться свойствами пе- риодичности косинуса: sin(x) = sin(2 + 2πn), где n есть любое целое число,
тогда sin(x) = sin(x%(2*math.pi))
. Для проверки использовать функцию math.sin(x)
3. Гиперболический косинус ch(x) = 1 +
x
2 2!
+
x
4 4!
+ · · · =
P

n=0
x
2n
(2n)!
. Для про- верки использовать функцию math.cosh(x).
4. Гиперболический косинус по формуле для экспоненты, оставляя только слагаемые с чётными n. Для проверки использовать функцию math.cosh(x).
5. Гиперболический синус sh(x) = x +
x
3 3!
+
x
5 5!
+ · · · =
P

n=0
x
2n+1
(2n+1)!
. Для про- верки использовать функцию math.sinh(x).

4.7. Задания на функции
109 6. Гиперболический синус по формуле для экспоненты, оставляя только сла- гаемые с нечётными n. Для проверки использовать функцию math.sinh(x).
7. Натуральный логарифм (формула работает при 0 < x 6 2):
ln(x) = (x − 1) −
(x − 1)
2 2
+
(x − 1)
3 3

(x − 1)
4 4
+ · · · =

X
n=1
(−1)
n−1
(x − 1)
n n
Чтобы найти логарифм для x > 2, необходимо представить его в виде ln(x) = ln(y · 2
p
) = p ln(2) + ln(y), где y < 2, а p натуральное число. Чтобы найти p и y, нужно в цикле делить x на 2 до тех пор, пока результат больше
2. Когда очередной результат деления станет меньше 2, этот результат и есть y, а число делений, за которое он достигнут – это p. Для проверки использовать функцию math.log(x).
8. Гамма-функция Γ(x) по формуле Эйлера:
Γ(x) =
1
x

Y
n=1 1 +
1
n

x
1 +
x n
Формула справедлива для x /
∈ {0, −1, −2, . . . }. Для проверки можно исполь- зовать math.gamma(x). Также, поскольку Γ(x + 1) = x! для натуральных x,
то для проверки можно использовать функцию math.factorial(x).
9. Функция ошибок, также известная как интеграл ошибок, интеграл вероят- ности, или функция Лапласа:
erf(x) =
2

π
Z
x
0
e

t
2
dt =
2

π

X
n=0
x
2n + 1
n
Y
i=1
−x
2
i
Для проверки использовать функцию scipy.special.erf(x).
10. Дополнительная функция ошибок:
erfc(x) = 1 − erf(x) =
2

π
Z

x e

t
2
dt =
e

x
2
x

π

X
n=0
(−1)
n
(2n)!
n!(2x)
2n
Для проверки использовать функцию scipy.special.erf(x).
Задание 12 (Танцы) Выполнять в каждом разделе по одному заданию в зависимости от номера в списке группы:
(n-1)%5+1
, где n — номер в списке.
1. два списка имён: первый — мальчиков, второй — девочек;
2. один список имён и число мальчиков, все имена мальчиков стоят в начале списка;

110
Глава 4. Функции
3. один список имён и число девочек, все имена девочек стоят в начале списка;
4. словарь, в котором в качестве ключа используется имя, а в каче- стве значения символ «м» для мальчиков и символ «ж» для девочек;
5. словарь, в котором в качестве ключей выступают символы «м» и
«ж», а в качестве соответствующих им значений — списки маль- чиков и девочек соответственно.
Проверьте работу функции на разных примерах:
• когда мальчиков и девочек поровну,
• когда мальчиков больше, чем девочек, и наоборот,
• когда есть ровно 1 мальчик или ровно 1 девочка,
• когда либо мальчиков, либо девочек нет вовсе.
Модифицируйте функцию так, чтобы она принимала второй необяза- тельный параметр — список уже составленных пар, участников кото- рых для составления пар использовать нельзя. В качестве значения по умолчанию для этого аргумента используйте пустой список. Проверьте работу функции, обратившись к ней:
• как и ранее (с одним аргументом), в этом случае результат должен совпасть с ранее полученным;
• передав все аргументы позиционно без имён;
• передав последний аргумент (список уже составленных пар) по име- ни;
• передав все аргументы по имени в произвольном порядке.
Задание 13 (Создание списков) Напишите функцию, принимающую от
1 до 3 параметров — целых чисел (как стандартная функция range).
Единственный обязательный аргумент — последнее число. Если поданы
2 аргумента, то первый интерпретируется как начальное число, второй
— как конечное (не включительно). Если поданы 3 аргумента, то тре- тий аргумент интерпретируется как шаг. Функция должна выдавать один из следующих списков:
1. квадратов чисел;
2. кубов чисел;
3. квадратных корней чисел;

4.7. Задания на функции
111 4. логарифмов чисел;
5. чисел последовательности Фибоначчи с номерами в указанных пре- делах.
Запускайте вашу функцию со всеми возможными вариантами по числу параметров: от 1 до 3.
Подсказка: проблему переменного числа параметров, из которых необязательным является в том числе первый, можно решить 2-мя способами. Во-первых, можно сопоставить всем параметрам нечисло- вые значения по умолчанию, обычно для этого используют специальное значение None. Тогда используя условный оператор можно определить,
сколько параметров реально заданы (не равны None). В зависимости от этого следует интерпретировать значение первого аргумента как: конец последовательности, если зада только 1 параметр; как начало, если за- даны 2 или 3. Во-вторых, можно проделать то же, используя синтаксис функции с произвольным числом параметров; в таком случае задавать значения по умолчанию не нужно, а полезно использовать стандартную функцию len, которая выдаст количество реально используемых пара- метров.
Задание 14 (Интернет-магазин) Решите задачу об интернет-торговле.
Несколько покупателей в течении года делали покупки в интернет- магазине. При каждой покупке фиксировались имя покупателя (строка)
и потраченная сумма (действительное число). Напишите функцию, рас- считывающую для каждого покупателя и выдающую в виде словаря по всем покупателям (вида имя:значение) один из следующих параметров:
1. число покупок;
2. среднюю сумму покупки;
3. максимальную сумму покупки;
4. минимальную сумму покупки;
5. общую сумму всех покупок.
На вход функции передаётся:
• либо 2 списка, в первом из которых имена покупателей (могут по- вторяться), во втором – суммы покупок;
• либо 1 список, состоящий из пар вида
(имя, сумма)
;
• либо словарь, в котором в качестве ключей используются имена, а в качестве значений — списки с суммами.

Глава 5
Массивы. Модуль numpy
Сам по себе «чистый» Python пригоден только для несложных вычислений.
Ключевая особенность Python — его расширяемость. Это, пожалуй, самый рас- ширяемый язык из получивших широкое распространение. Как следствие этого для Python не только написаны и приспособлены многочисленные библиотеки алгоритмов на C и Fortran, но и имеются возможности использования других программных средств и математических пакетов, в частности, R и SciLab, а так- же графопостроителей, например, Gnuplot и PLPlot.
Ключевыми модулями для превращения Python в математический пакет яв- ляются numpy и matplotlib.
numpy
— это модуль (в действительности, набор модулей) языка Python, до- бавляющая поддержку больших многомерных массивов и матриц, вместе с боль- шим набором высокоуровневых (и очень быстрых) математических функций для операций с этими массивами.
matplotlib
— модуль (в действительности, набор модулей) на языке про- граммирования Python для визуализации данных двумерной (2D) графикой (3D
графика также поддерживается). Получаемые изображения могут быть исполь- зованы в качестве иллюстраций в публикациях.
Кроме numpy и matplotlib популярностью пользуются scipy для специализи- рованных математических вычислений (поиск минимума и корней функции мно- гих переменных, аппроксимация сплайнами, вейвлет-преобразования), sympy для символьных вычислений (аналитическое взятие интегралов, упрощение матема- тических выражений), ffnet для построения искусственных нейронных сетей,
pyopencl
/pycuda для вычисления на видеокартах и некоторые другие. Возмож- ности numpy и scipy покрывают практически все потребности в математических алгоритмах.

5.1. Создание и индексация массивов
113
(a)
(b)
Рис. 5.1. Одномерный — (a) и двумерный — (b) массивы.
5.1
Создание и индексация массивов
Массив — упорядоченный набор значений одного типа, расположенных в па- мяти непосредственно друг за другом. При этом доступ к отдельным элемен- там массива осуществляется с помощью индексации, то есть через ссылку на массив с указанием номера (индекса) нужного элемента. Это возможно потому,
что все значения имеют один и тот же тип, занимая одно и то же количество байт памяти; таким образом, зная ссылку и номер элемента, можно вычислить,
где он расположен в памяти. Количество используемых индексов массива может быть различным: массивы с одним индексом называют одномерными, с двумя —
двумерными, и т. д. Одномерный массив («колонка», «столбец») примерно соот- ветствует вектору в математике (на рис. 5.1(а) a[4] == 56, т.е. четвёртый эле- мент массива а равен 56); двумерный — матрице (на рис. 5.1(b) можно писать
A[1][6] == 22
, можно A[1, 6] == 22). Чаще всего применяются массивы с од- ним или двумя индексами; реже — с тремя; ещё большее количество индексов встречается крайне редко.
Как правило, в программировании массивы делятся на статические и ди- намические. Статический массив — массив, размер которого определяется на момент компиляции программы. В языках с динамической типизацией таких,
как Python, они не применяются. Динамический массив — массив, размер кото- рого задаётся во время работы программы. То есть при запуске программы этот массив не занимает нисколько памяти компьютера (может быть, за исключе- нием памяти, необходимой для хранения ссылки). Динамические массивы могут поддерживать и не поддерживать изменение размера в процессе исполнения про- граммы. Массивы в Python не поддерживают явное изменение размера: у них, в отличие от списков, нет методов append и extend, позволяющих добавлять эле- менты, и методов pop и remove, позволяющих их удалять. Если нужно изменить размер массива, это можно сделать путём переприсваивания имени переменной,

114
Глава 5. Массивы. Модуль numpy обозначающей массив, нового значения, соответствующего новой области памя- ти, больше или меньше прежней разными способами.
Базовый оператор создания массива называется array. С его помощью можно создать новый массив с нуля или превратить в массив уже существующий список.
Вот пример:
f r
o m
numpy i
m p
o r
t
*
A = array ([0.1 , 0.4 , 3 , -11.2 , 9])
p r
i n
t
( A )
p r
i n
t
(
t y
p e
( A ))
В первой строке из модуля numpy импортируются все функции и константы.
Вывод программы следующий:
[0.1 0.4 3.
-11.2 9. ]

Функция array() трансформирует вложенные последовательности в много- мерные массивы. Тип элементов массива зависит от типа элементов исходной последовательности:
B = array ([[1 , 2 , 3] , [4 , 5 , 6]])
p r
i n
t
( B )
Вывод:
[[1 2 3]
[4 5 6]]
Тип элементов массива можно определить в момент создания с помощью име- нованного аргумента dtype. Модуль numpy предоставляет выбор из следующих встроенных типов: bool (логическое значение), character (символ), int8, int16,
int32
, int64 (знаковые целые числа размеров в 8, 16, 32 и 64 бита соответствен- но), uint8, uint16, uint32, uint64 (беззнаковые целые числа размеров в 8, 16, 32
и 64 бита соответственно), float32 и float64 (действительные числа одинарной и двойной точности), complex64 и complex128 (комплексные числа одинарной и двойной точности), а также возможность определить собственные типы данных,
в том числе и составные.
C = array ([[1 , 2 , 3] , [4 , 5 , 6]] , dtype =
f l
o a
t
)
p r
i n
t
( C )
Вывод:
[[ 1.
2.
3.]
[ 4.
5.
6.]]
Можно создать массив из диапазона:

5.1. Создание и индексация массивов
115
f r
o m
numpy i
m p
o r
t
*
L =
r a
n g
e
(5)
A = array ( L )
p r
i n
t
( A )
Вывод:
[0 1 2 3 4]
Отсюда видно, что в первом случае массив состоит из действительных чисел,
так как при определении часть его значений задана в виде десятичных дробей. В
numpy есть несколько действительнозначных типов, базовый тип соответствует действительным числам Python и называется float64. Второй массив состоит из целых чисел, потому что создан из диапазона range, в который входят толь- ко целые числа. На 64-битных операционных системах элементы такого списка будут автоматически приведены к целому типу int64, на 32-битных — к типу int32
В numpy есть функция arange, позволяющая сразу создать массив-диапазон,
причём можно использовать дробный шаг. Вот программа, рассчитывающая зна- чения синуса на одном периоде с шагом π/6:
f r
o m
numpy i
m p
o r
t
*
a1 = arange (0 , 2* pi , pi /6)
s1 = sin ( a1 )
f o
r j
i n
r a
n g
e
(
l e
n
( a1 )):
p r
i n
t
( a1 [ j ] , s1 [ j ])
А вот её вывод:
0.0 0.0 0.523598775598 0.5 1.0471975512 0.866025403784 1.57079632679 1.0 2.09439510239 0.866025403784 2.61799387799 0.5 3.14159265359 1.22464679915e-16 3.66519142919 -0.5 4.18879020479 -0.866025403784 4.71238898038 -1.0 5.23598775598 -0.866025403784 5.75958653158 -0.5
Кроме arange есть ещё функция linspace, тоже создающая массив-диапазон.

Функция ошибок (функция Лапласа или интеграл вероятности) — неэлементарная функция, возникающая в теории вероятностей, статистике и теории дифференциальных уравнений в частных производных. Она определяется как

operatorname{erf},x = frac{2}{sqrt{pi}}intlimits_0^x e^{-t^2},mathrm dt.

Дополнительная функция ошибок, обозначаемая operatorname{erfc},x (иногда применяется обозначение operatorname{Erf},x) определяется через функцию ошибок:

operatorname{erfc},x = 1-operatorname{erf},x = frac{2}{sqrt{pi}} intlimits_x^{infty} e^{-t^2},mathrm dt.

Комплексная функция ошибок, обозначаемая w(x), также определяется через функцию ошибок:

w(x) = e^{-x^2}operatorname{erfc},(-ix).

Содержание

  • 1 Свойства
  • 2 Применение
  • 3 Асимптотическое разложение
  • 4 Родственные функции
    • 4.1 Обобщённые функции ошибок
    • 4.2 Итерированные интегралы дополнительной функции ошибок
  • 5 Реализации
  • 6 См. также
  • 7 Литература
  • 8 Примечания
  • 9 Ссылки

Свойства[править]

  • Функция ошибок нечётна:
operatorname{erf},(-x) = -operatorname{erf},x.
  • Для любого комплексного x выполняется
operatorname{erf},bar{x} = overline{operatorname{erf},x}

где черта обозначает комплексное сопряжение числа x.

  • Функция ошибок не может быть представлена через элементарные функции, но, разлагая интегрируемое выражение в ряд Тейлора и интегрируя почленно, мы можем получить её представление в виде ряда:
operatorname{erf},x= frac{2}{sqrt{pi}}sum_{n=0}^infinfrac{(-1)^n x^{2n+1}}{n! (2n+1)} =frac{2}{sqrt{pi}} left(x-frac{x^3}{3}+frac{x^5}{10}-frac{x^7}{42}+frac{x^9}{216}- cdotsright)

Это равенство выполняется (и ряд сходится) как для любого вещественного x[источник не указан 3971 день], так и на всей комплексной плоскости. Последовательность знаменателей образует последовательность A007680 в OEIS.

  • Для итеративного вычисления элементов ряда полезно представить его в альтернативном виде:
operatorname{erf},x= frac{2}{sqrt{pi}}sum_{n=0}^infinleft(x prod_{i=1}^n{frac{-(2i-1) x^2}{i (2i+1)}}right) = frac{2}{sqrt{pi}} sum_{n=0}^infin frac{x}{2n+1} prod_{i=1}^n frac{-x^2}{i}

поскольку frac{-(2i-1) x^2}{i (2i+1)} — сомножитель, превращающий i-й член ряда в (i+1)-й, считая первым членом x.

  • Функция ошибок на бесконечности равна единице; однако это справедливо только при приближении к бесконечности по вещественной оси, так как:
  • При рассмотрении функции ошибок в комплексной плоскости точка z=infty будет для неё существенно особой.
  • Производная функции ошибок выводится непосредственно из определения функции:
frac{d}{dx},operatorname{erf},x=frac{2}{sqrt{pi}},e^{-x^2}.
  • Обратная функция ошибок представляет собой ряд
operatorname{erf}^{-1},x=sum_{k=0}^infinfrac{c_k}{2k+1}left (frac{sqrt{pi}}{2}xright )^{2k+1}, ,!

где c0 = 1 и

c_k=sum_{m=0}^{k-1}frac{c_m c_{k-1-m}}{(m+1)(2m+1)} = left{1,1,frac{7}{6},frac{127}{90},ldotsright}.

Поэтому ряд можно представить в следующем виде (заметим, что дроби сокращены):

operatorname{erf}^{-1},x=frac{1}{2}sqrt{pi}left (x+frac{pi x^3}{12}+frac{7pi^2 x^5}{480}+frac{127pi^3 x^7}{40320}+frac{4369pi^4 x^9}{5806080}+frac{34807pi^5 x^{11}}{182476800}+dotsright ). ,![2]

Последовательности числителей и знаменателей после сокращения — A092676 и A132467 в OEIS; последовательность числителей до сокращения — A002067 в OEIS.

Ошибка создания миниатюры:

Дополнительная функция ошибок

Применение[править]

Если набор случайных чисел подчиняется нормальному распределению со стандартным отклонением sigma, то вероятность, что число отклонится от среднего не более чем на a, равна operatorname{erf},frac{a}{sigma sqrt{2}}.

Функция ошибок и дополнительная функция ошибок встречаются в решении некоторых дифференциальных уравнений, например, уравнения теплопроводности с граничными условиями описываемыми функцией Хевисайда («ступенькой»).

В системах цифровой оптической коммуникации, вероятность ошибки на бит также выражается формулой, использующей функцию ошибок.

Асимптотическое разложение[править]

При больших x полезно асимптотическое разложение для дополнительной функции ошибок:

operatorname{erfc},x = frac{e^{-x^2}}{xsqrt{pi}}left [1+sum_{n=1}^infty (-1)^n frac{1cdot3cdot5cdots(2n-1)}{(2x^2)^n}right ]=frac{e^{-x^2}}{xsqrt{pi}}sum_{n=0}^infty (-1)^n frac{(2n)!}{n!(2x)^{2n}}.,

Хотя для любого конечного x этот ряд расходится, на практике первых нескольких членов достаточно для вычисления operatorname{erfc},x с хорошей точностью, в то время как ряд Тейлора сходится очень медленно.

Другое приближение даётся формулой

(operatorname{erf},x)^2approx 1-expleft(-x^2frac{4/pi+ax^2}{1+ax^2}right)

где

a = frac{8}{3pi}frac{3 - pi}{pi - 4}.

Родственные функции[править]

С точностью до масштаба и сдвига, функция ошибок совпадает с нормальным интегральным распределением, обозначаемым Phi(x)

Phi(x) = frac{1}{2}(1+operatorname{erf},frac{x}{sqrt{2}},).

Обратная функция к Phi, известная как нормальная квантильная функция, иногда обозначается operatorname{probit} и выражается через нормальную функцию ошибок как

operatorname{probit},p = Phi^{-1}(p) = sqrt{2},operatorname{erf}^{-1}(2p-1).

Нормальное интегральное распределение чаще применяется в теории вероятностей и математической статистике, в то время как функция ошибок чаще применяется в других разделах математики.

Функция ошибок является частным случаем функции Миттаг-Леффлера, а также может быть представлена как вырожденная гипергеометрическая функция (функция Куммера):

operatorname{erf},x= frac{2x}{sqrt{pi}},_1F_1left(frac{1}{2},frac{3}{2},-x^2right).

Функция ошибок выражается также через интеграл Френеля. В терминах регуляризованной неполной гамма-функции P и неполной гамма-функции,

operatorname{erf},x=operatorname{sign},x,Pleft(frac{1}{2}, x^2right)={operatorname{sign},x over sqrt{pi}}gammaleft(frac{1}{2}, x^2right).

Обобщённые функции ошибок[править]

Некоторые авторы обсуждают более общие функции

E_n(x) = frac{n!}{sqrt{pi}} intlimits_0^x e^{-t^n},mathrm dt =frac{n!}{sqrt{pi}}sum_{p=0}^infin(-1)^pfrac{x^{np+1}}{(np+1)p!},.

Примечательными частными случаями являются:

После деления на n! все E_n с нечётными n выглядят похоже (но не идентично). Все E_n с чётными n тоже выглядят похоже, но не идентично, после деления на n!. Все обобщённые функции ошибок с n>0 выглядят похоже на полуоси x>0.

На полуоси x>0 все обобщённые функции могут быть выражены через гамма-функцию:

E_n(x) = frac{Gamma(n)left(Gammaleft(frac{1}{n}right)-Gammaleft(frac{1}{n},x^nright)right)}{sqrtpi}, quad quad x>0

Следовательно, мы можем выразить функцию ошибок через гамма-функцию:

operatorname{erf},x = 1 - frac{Gammaleft(frac{1}{2},x^2right)}{sqrtpi}

Итерированные интегралы дополнительной функции ошибок[править]

Итерированные интегралы дополнительной функции ошибок определяются как

i^n,operatorname{erfc},z = intlimits_z^infty i^{n-1},operatorname{erfc},zeta,dzeta.,

Их можно разложить в ряд:

i^n,operatorname{erfc},z = sum_{j=0}^infty frac{(-z)^j}{2^{n-j}j!,Gamma left( 1 + frac{n-j}{2}right)},,

откуда следуют свойства симметрии

i^{2m},operatorname{erfc},(-z) = -i^{2m},operatorname{erfc},z + sum_{q=0}^m frac{z^{2q}}{2^{2(m-q)-1}(2q)!(m-q)!}

и

i^{2m+1},operatorname{erfc},(-z) =i^{2m+1},operatorname{erfc},z + sum_{q=0}^m frac{z^{2q+1}}{2^{2(m-q)-1}(2q+1)! (m-q)!},.

Реализации[править]

В стандарте языка Си (ISO/IEC 9899:1999, пункт 7.12.8) предусмотрены функция ошибок operatorname{erf} и дополнительная функция ошибок operatorname{erfc}. Функции объявлены в заголовочных файлах math.h (для Си) или cmath (для C++). Там же объявлены пары функций erff(), erfcf() и erfl(), erfcl(). Первая пара получает и возвращает значения типа float, а вторая — значения типа long double. Соответствующие функции также содержатся в библиотеке Math проекта «Boost».

В языке Java стандартная библиотека математических функций java.lang.Math не содержит[1] функцию ошибок. Класс Erf можно найти в пакете org.apache.commons.math.special из не стандартной библиотеки, поставляемой[2] Apache.

Системы компьютерной алгебры Maple[3], Matlab[4], Mathematica и Maxima[5] содержат обычную и дополнительную функции ошибок, а также обратные к ним функции.

В языке Python функция ошибок доступна[3] из стандартной библиотеки math, начиная с версии 2.7. Также функция ошибок, дополнительная функция ошибок и многие другие специальные функции определены в модуле Special проекта SciPy[6].

В языке Erlang функция ошибок и дополнительная функция ошибок доступны из стандартного модуля math[4].

См. также[править]

  • Функция Гаусса
  • Функция Доусона

Литература[править]

  • Milton Abramowitz and Irene A. Stegun, eds. Handbook of Mathematical Functions with Formulas, Graphs, and Mathematical Tables. New York: Dover, 1972. (См. часть 7)
  • Nikolai G. Lehtinen «Error functions», April 2010 [7]

Примечания[править]

  1. Math (Java Platform SE 6)
  2. [1]
  3. 9.2. math — Mathematical functions — Python 2.7.10rc0 documentation
  4. Язык Erlang. Описание функций стандартного модуля math.

Ссылки[править]

  • MathWorld — Erf
  • Онлайновый калькулятор Erf и много других специальных функций (до 6 знаков)
  • Онлайновый калькулятор, вычисляющий в том числе Erf
Error function
Plot of the error function

Plot of the error function

General information
General definition {displaystyle operatorname {erf} z={frac {2}{sqrt {pi }}}int _{0}^{z}e^{-t^{2}},mathrm {d} t}
Fields of application Probability, thermodynamics
Domain, Codomain and Image
Domain mathbb {C}
Image {displaystyle left(-1,1right)}
Basic features
Parity Odd
Specific features
Root 0
Derivative {displaystyle {frac {mathrm {d} }{mathrm {d} z}}operatorname {erf} z={frac {2}{sqrt {pi }}}e^{-z^{2}}}
Antiderivative {displaystyle int operatorname {erf} z,dz=zoperatorname {erf} z+{frac {e^{-z^{2}}}{sqrt {pi }}}+C}
Series definition
Taylor series {displaystyle operatorname {erf} z={frac {2}{sqrt {pi }}}sum _{n=0}^{infty }{frac {z}{2n+1}}prod _{k=1}^{n}{frac {-z^{2}}{k}}}

In mathematics, the error function (also called the Gauss error function), often denoted by erf, is a complex function of a complex variable defined as:[1]

{displaystyle operatorname {erf} z={frac {2}{sqrt {pi }}}int _{0}^{z}e^{-t^{2}},mathrm {d} t.}

This integral is a special (non-elementary) sigmoid function that occurs often in probability, statistics, and partial differential equations. In many of these applications, the function argument is a real number. If the function argument is real, then the function value is also real.

In statistics, for non-negative values of x, the error function has the following interpretation: for a random variable Y that is normally distributed with mean 0 and standard deviation 1/2, erf x is the probability that Y falls in the range [−x, x].

Two closely related functions are the complementary error function (erfc) defined as

{displaystyle operatorname {erfc} z=1-operatorname {erf} z,}

and the imaginary error function (erfi) defined as

{displaystyle operatorname {erfi} z=-ioperatorname {erf} iz,}

where i is the imaginary unit

Name[edit]

The name «error function» and its abbreviation erf were proposed by J. W. L. Glaisher in 1871 on account of its connection with «the theory of Probability, and notably the theory of Errors.»[2] The error function complement was also discussed by Glaisher in a separate publication in the same year.[3]
For the «law of facility» of errors whose density is given by

{displaystyle f(x)=left({frac {c}{pi }}right)^{frac {1}{2}}e^{-cx^{2}}}

(the normal distribution), Glaisher calculates the probability of an error lying between p and q as:

{displaystyle left({frac {c}{pi }}right)^{frac {1}{2}}int _{p}^{q}e^{-cx^{2}},mathrm {d} x={tfrac {1}{2}}left(operatorname {erf} left(q{sqrt {c}}right)-operatorname {erf} left(p{sqrt {c}}right)right).}

Plot of the error function Erf(z) in the complex plane from -2-2i to 2+2i with colors created with Mathematica 13.1 function ComplexPlot3D

Plot of the error function Erf(z) in the complex plane from -2-2i to 2+2i with colors created with Mathematica 13.1 function ComplexPlot3D

Applications[edit]

When the results of a series of measurements are described by a normal distribution with standard deviation σ and expected value 0, then erf (a/σ 2) is the probability that the error of a single measurement lies between a and +a, for positive a. This is useful, for example, in determining the bit error rate of a digital communication system.

The error and complementary error functions occur, for example, in solutions of the heat equation when boundary conditions are given by the Heaviside step function.

The error function and its approximations can be used to estimate results that hold with high probability or with low probability. Given a random variable X ~ Norm[μ,σ] (a normal distribution with mean μ and standard deviation σ) and a constant L < μ:

{displaystyle {begin{aligned}Pr[Xleq L]&={frac {1}{2}}+{frac {1}{2}}operatorname {erf} {frac {L-mu }{{sqrt {2}}sigma }}&approx Aexp left(-Bleft({frac {L-mu }{sigma }}right)^{2}right)end{aligned}}}

where A and B are certain numeric constants. If L is sufficiently far from the mean, specifically μLσln k, then:

{displaystyle Pr[Xleq L]leq Aexp(-Bln {k})={frac {A}{k^{B}}}}

so the probability goes to 0 as k → ∞.

The probability for X being in the interval [La, Lb] can be derived as

{displaystyle {begin{aligned}Pr[L_{a}leq Xleq L_{b}]&=int _{L_{a}}^{L_{b}}{frac {1}{{sqrt {2pi }}sigma }}exp left(-{frac {(x-mu )^{2}}{2sigma ^{2}}}right),mathrm {d} x&={frac {1}{2}}left(operatorname {erf} {frac {L_{b}-mu }{{sqrt {2}}sigma }}-operatorname {erf} {frac {L_{a}-mu }{{sqrt {2}}sigma }}right).end{aligned}}}

Properties[edit]

Integrand exp(−z2)

erf z

The property erf (−z) = −erf z means that the error function is an odd function. This directly results from the fact that the integrand et2 is an even function (the antiderivative of an even function which is zero at the origin is an odd function and vice versa).

Since the error function is an entire function which takes real numbers to real numbers, for any complex number z:

{displaystyle operatorname {erf} {overline {z}}={overline {operatorname {erf} z}}}

where z is the complex conjugate of z.

The integrand f = exp(−z2) and f = erf z are shown in the complex z-plane in the figures at right with domain coloring.

The error function at +∞ is exactly 1 (see Gaussian integral). At the real axis, erf z approaches unity at z → +∞ and −1 at z → −∞. At the imaginary axis, it tends to ±i.

Taylor series[edit]

The error function is an entire function; it has no singularities (except that at infinity) and its Taylor expansion always converges, but is famously known «[…] for its bad convergence if x > 1[4]

The defining integral cannot be evaluated in closed form in terms of elementary functions, but by expanding the integrand ez2 into its Maclaurin series and integrating term by term, one obtains the error function’s Maclaurin series as:

{displaystyle {begin{aligned}operatorname {erf} z&={frac {2}{sqrt {pi }}}sum _{n=0}^{infty }{frac {(-1)^{n}z^{2n+1}}{n!(2n+1)}}[6pt]&={frac {2}{sqrt {pi }}}left(z-{frac {z^{3}}{3}}+{frac {z^{5}}{10}}-{frac {z^{7}}{42}}+{frac {z^{9}}{216}}-cdots right)end{aligned}}}

which holds for every complex number z. The denominator terms are sequence A007680 in the OEIS.

For iterative calculation of the above series, the following alternative formulation may be useful:

{displaystyle {begin{aligned}operatorname {erf} z&={frac {2}{sqrt {pi }}}sum _{n=0}^{infty }left(zprod _{k=1}^{n}{frac {-(2k-1)z^{2}}{k(2k+1)}}right)[6pt]&={frac {2}{sqrt {pi }}}sum _{n=0}^{infty }{frac {z}{2n+1}}prod _{k=1}^{n}{frac {-z^{2}}{k}}end{aligned}}}

because −(2k − 1)z2/k(2k + 1) expresses the multiplier to turn the kth term into the (k + 1)th term (considering z as the first term).

The imaginary error function has a very similar Maclaurin series, which is:

{displaystyle {begin{aligned}operatorname {erfi} z&={frac {2}{sqrt {pi }}}sum _{n=0}^{infty }{frac {z^{2n+1}}{n!(2n+1)}}[6pt]&={frac {2}{sqrt {pi }}}left(z+{frac {z^{3}}{3}}+{frac {z^{5}}{10}}+{frac {z^{7}}{42}}+{frac {z^{9}}{216}}+cdots right)end{aligned}}}

which holds for every complex number z.

Derivative and integral[edit]

The derivative of the error function follows immediately from its definition:

{displaystyle {frac {mathrm {d} }{mathrm {d} z}}operatorname {erf} z={frac {2}{sqrt {pi }}}e^{-z^{2}}.}

From this, the derivative of the imaginary error function is also immediate:

{displaystyle {frac {d}{dz}}operatorname {erfi} z={frac {2}{sqrt {pi }}}e^{z^{2}}.}

An antiderivative of the error function, obtainable by integration by parts, is

{displaystyle zoperatorname {erf} z+{frac {e^{-z^{2}}}{sqrt {pi }}}.}

An antiderivative of the imaginary error function, also obtainable by integration by parts, is

{displaystyle zoperatorname {erfi} z-{frac {e^{z^{2}}}{sqrt {pi }}}.}

Higher order derivatives are given by

{displaystyle operatorname {erf} ^{(k)}z={frac {2(-1)^{k-1}}{sqrt {pi }}}{mathit {H}}_{k-1}(z)e^{-z^{2}}={frac {2}{sqrt {pi }}}{frac {mathrm {d} ^{k-1}}{mathrm {d} z^{k-1}}}left(e^{-z^{2}}right),qquad k=1,2,dots }

where H are the physicists’ Hermite polynomials.[5]

Bürmann series[edit]

An expansion,[6] which converges more rapidly for all real values of x than a Taylor expansion, is obtained by using Hans Heinrich Bürmann’s theorem:[7]

{displaystyle {begin{aligned}operatorname {erf} x&={frac {2}{sqrt {pi }}}operatorname {sgn} xcdot {sqrt {1-e^{-x^{2}}}}left(1-{frac {1}{12}}left(1-e^{-x^{2}}right)-{frac {7}{480}}left(1-e^{-x^{2}}right)^{2}-{frac {5}{896}}left(1-e^{-x^{2}}right)^{3}-{frac {787}{276480}}left(1-e^{-x^{2}}right)^{4}-cdots right)[10pt]&={frac {2}{sqrt {pi }}}operatorname {sgn} xcdot {sqrt {1-e^{-x^{2}}}}left({frac {sqrt {pi }}{2}}+sum _{k=1}^{infty }c_{k}e^{-kx^{2}}right).end{aligned}}}

where sgn is the sign function. By keeping only the first two coefficients and choosing c1 = 31/200 and c2 = −341/8000, the resulting approximation shows its largest relative error at x = ±1.3796, where it is less than 0.0036127:

{displaystyle operatorname {erf} xapprox {frac {2}{sqrt {pi }}}operatorname {sgn} xcdot {sqrt {1-e^{-x^{2}}}}left({frac {sqrt {pi }}{2}}+{frac {31}{200}}e^{-x^{2}}-{frac {341}{8000}}e^{-2x^{2}}right).}

Inverse functions[edit]

Given a complex number z, there is not a unique complex number w satisfying erf w = z, so a true inverse function would be multivalued. However, for −1 < x < 1, there is a unique real number denoted erf−1 x satisfying

{displaystyle operatorname {erf} left(operatorname {erf} ^{-1}xright)=x.}

The inverse error function is usually defined with domain (−1,1), and it is restricted to this domain in many computer algebra systems. However, it can be extended to the disk |z| < 1 of the complex plane, using the Maclaurin series

{displaystyle operatorname {erf} ^{-1}z=sum _{k=0}^{infty }{frac {c_{k}}{2k+1}}left({frac {sqrt {pi }}{2}}zright)^{2k+1},}

where c0 = 1 and

{displaystyle {begin{aligned}c_{k}&=sum _{m=0}^{k-1}{frac {c_{m}c_{k-1-m}}{(m+1)(2m+1)}}&=left{1,1,{frac {7}{6}},{frac {127}{90}},{frac {4369}{2520}},{frac {34807}{16200}},ldots right}.end{aligned}}}

So we have the series expansion (common factors have been canceled from numerators and denominators):

{displaystyle operatorname {erf} ^{-1}z={frac {sqrt {pi }}{2}}left(z+{frac {pi }{12}}z^{3}+{frac {7pi ^{2}}{480}}z^{5}+{frac {127pi ^{3}}{40320}}z^{7}+{frac {4369pi ^{4}}{5806080}}z^{9}+{frac {34807pi ^{5}}{182476800}}z^{11}+cdots right).}

(After cancellation the numerator/denominator fractions are entries OEIS: A092676/OEIS: A092677 in the OEIS; without cancellation the numerator terms are given in entry OEIS: A002067.) The error function’s value at ±∞ is equal to ±1.

For |z| < 1, we have erf(erf−1 z) = z.

The inverse complementary error function is defined as

{displaystyle operatorname {erfc} ^{-1}(1-z)=operatorname {erf} ^{-1}z.}

For real x, there is a unique real number erfi−1 x satisfying erfi(erfi−1 x) = x. The inverse imaginary error function is defined as erfi−1 x.[8]

For any real x, Newton’s method can be used to compute erfi−1 x, and for −1 ≤ x ≤ 1, the following Maclaurin series converges:

{displaystyle operatorname {erfi} ^{-1}z=sum _{k=0}^{infty }{frac {(-1)^{k}c_{k}}{2k+1}}left({frac {sqrt {pi }}{2}}zright)^{2k+1},}

where ck is defined as above.

Asymptotic expansion[edit]

A useful asymptotic expansion of the complementary error function (and therefore also of the error function) for large real x is

{displaystyle {begin{aligned}operatorname {erfc} x&={frac {e^{-x^{2}}}{x{sqrt {pi }}}}left(1+sum _{n=1}^{infty }(-1)^{n}{frac {1cdot 3cdot 5cdots (2n-1)}{left(2x^{2}right)^{n}}}right)[6pt]&={frac {e^{-x^{2}}}{x{sqrt {pi }}}}sum _{n=0}^{infty }(-1)^{n}{frac {(2n-1)!!}{left(2x^{2}right)^{n}}},end{aligned}}}

where (2n − 1)!! is the double factorial of (2n − 1), which is the product of all odd numbers up to (2n − 1). This series diverges for every finite x, and its meaning as asymptotic expansion is that for any integer N ≥ 1 one has

{displaystyle operatorname {erfc} x={frac {e^{-x^{2}}}{x{sqrt {pi }}}}sum _{n=0}^{N-1}(-1)^{n}{frac {(2n-1)!!}{left(2x^{2}right)^{n}}}+R_{N}(x)}

where the remainder, in Landau notation, is

{displaystyle R_{N}(x)=Oleft(x^{-(1+2N)}e^{-x^{2}}right)}

as x → ∞.

Indeed, the exact value of the remainder is

{displaystyle R_{N}(x):={frac {(-1)^{N}}{sqrt {pi }}}2^{1-2N}{frac {(2N)!}{N!}}int _{x}^{infty }t^{-2N}e^{-t^{2}},mathrm {d} t,}

which follows easily by induction, writing

{displaystyle e^{-t^{2}}=-(2t)^{-1}left(e^{-t^{2}}right)'}

and integrating by parts.

For large enough values of x, only the first few terms of this asymptotic expansion are needed to obtain a good approximation of erfc x (while for not too large values of x, the above Taylor expansion at 0 provides a very fast convergence).

Continued fraction expansion[edit]

A continued fraction expansion of the complementary error function is:[9]

{displaystyle operatorname {erfc} z={frac {z}{sqrt {pi }}}e^{-z^{2}}{cfrac {1}{z^{2}+{cfrac {a_{1}}{1+{cfrac {a_{2}}{z^{2}+{cfrac {a_{3}}{1+dotsb }}}}}}}},qquad a_{m}={frac {m}{2}}.}

Integral of error function with Gaussian density function[edit]

{displaystyle int _{-infty }^{infty }operatorname {erf} left(ax+bright){frac {1}{sqrt {2pi sigma ^{2}}}}exp left(-{frac {(x-mu )^{2}}{2sigma ^{2}}}right),mathrm {d} x=operatorname {erf} {frac {amu +b}{sqrt {1+2a^{2}sigma ^{2}}}},qquad a,b,mu ,sigma in mathbb {R} }

which appears related to Ng and Geller, formula 13 in section 4.3[10] with a change of variables.

Factorial series[edit]

The inverse factorial series:

{displaystyle {begin{aligned}operatorname {erfc} z&={frac {e^{-z^{2}}}{{sqrt {pi }},z}}sum _{n=0}^{infty }{frac {(-1)^{n}Q_{n}}{{(z^{2}+1)}^{bar {n}}}}&={frac {e^{-z^{2}}}{{sqrt {pi }},z}}left(1-{frac {1}{2}}{frac {1}{(z^{2}+1)}}+{frac {1}{4}}{frac {1}{(z^{2}+1)(z^{2}+2)}}-cdots right)end{aligned}}}

converges for Re(z2) > 0. Here

{displaystyle {begin{aligned}Q_{n}&{overset {text{def}}{{}={}}}{frac {1}{Gamma left({frac {1}{2}}right)}}int _{0}^{infty }tau (tau -1)cdots (tau -n+1)tau ^{-{frac {1}{2}}}e^{-tau },dtau &=sum _{k=0}^{n}left({tfrac {1}{2}}right)^{bar {k}}s(n,k),end{aligned}}}

zn denotes the rising factorial, and s(n,k) denotes a signed Stirling number of the first kind.[11][12]
There also exists a representation by an infinite sum containing the double factorial:

{displaystyle operatorname {erf} z={frac {2}{sqrt {pi }}}sum _{n=0}^{infty }{frac {(-2)^{n}(2n-1)!!}{(2n+1)!}}z^{2n+1}}

Numerical approximations[edit]

Approximation with elementary functions[edit]

  • Abramowitz and Stegun give several approximations of varying accuracy (equations 7.1.25–28). This allows one to choose the fastest approximation suitable for a given application. In order of increasing accuracy, they are:
    {displaystyle operatorname {erf} xapprox 1-{frac {1}{left(1+a_{1}x+a_{2}x^{2}+a_{3}x^{3}+a_{4}x^{4}right)^{4}}},qquad xgeq 0}

    (maximum error: 5×10−4)

    where a1 = 0.278393, a2 = 0.230389, a3 = 0.000972, a4 = 0.078108

    {displaystyle operatorname {erf} xapprox 1-left(a_{1}t+a_{2}t^{2}+a_{3}t^{3}right)e^{-x^{2}},quad t={frac {1}{1+px}},qquad xgeq 0}

    (maximum error: 2.5×10−5)

    where p = 0.47047, a1 = 0.3480242, a2 = −0.0958798, a3 = 0.7478556

    {displaystyle operatorname {erf} xapprox 1-{frac {1}{left(1+a_{1}x+a_{2}x^{2}+cdots +a_{6}x^{6}right)^{16}}},qquad xgeq 0}

    (maximum error: 3×10−7)

    where a1 = 0.0705230784, a2 = 0.0422820123, a3 = 0.0092705272, a4 = 0.0001520143, a5 = 0.0002765672, a6 = 0.0000430638

    {displaystyle operatorname {erf} xapprox 1-left(a_{1}t+a_{2}t^{2}+cdots +a_{5}t^{5}right)e^{-x^{2}},quad t={frac {1}{1+px}}}

    (maximum error: 1.5×10−7)

    where p = 0.3275911, a1 = 0.254829592, a2 = −0.284496736, a3 = 1.421413741, a4 = −1.453152027, a5 = 1.061405429

    All of these approximations are valid for x ≥ 0. To use these approximations for negative x, use the fact that erf x is an odd function, so erf x = −erf(−x).

  • Exponential bounds and a pure exponential approximation for the complementary error function are given by[13]
    {displaystyle {begin{aligned}operatorname {erfc} x&leq {tfrac {1}{2}}e^{-2x^{2}}+{tfrac {1}{2}}e^{-x^{2}}leq e^{-x^{2}},&quad x&>0operatorname {erfc} x&approx {tfrac {1}{6}}e^{-x^{2}}+{tfrac {1}{2}}e^{-{frac {4}{3}}x^{2}},&quad x&>0.end{aligned}}}
  • The above have been generalized to sums of N exponentials[14] with increasing accuracy in terms of N so that erfc x can be accurately approximated or bounded by 2(2x), where
    {displaystyle {tilde {Q}}(x)=sum _{n=1}^{N}a_{n}e^{-b_{n}x^{2}}.}

    In particular, there is a systematic methodology to solve the numerical coefficients {(an,bn)}N
    n = 1
    that yield a minimax approximation or bound for the closely related Q-function: Q(x) ≈ (x), Q(x) ≤ (x), or Q(x) ≥ (x) for x ≥ 0. The coefficients {(an,bn)}N
    n = 1
    for many variations of the exponential approximations and bounds up to N = 25 have been released to open access as a comprehensive dataset.[15]

  • A tight approximation of the complementary error function for x ∈ [0,∞) is given by Karagiannidis & Lioumpas (2007)[16] who showed for the appropriate choice of parameters {A,B} that
    {displaystyle operatorname {erfc} xapprox {frac {left(1-e^{-Ax}right)e^{-x^{2}}}{B{sqrt {pi }}x}}.}

    They determined {A,B} = {1.98,1.135}, which gave a good approximation for all x ≥ 0. Alternative coefficients are also available for tailoring accuracy for a specific application or transforming the expression into a tight bound.[17]

  • A single-term lower bound is[18]

    {displaystyle operatorname {erfc} xgeq {sqrt {frac {2e}{pi }}}{frac {sqrt {beta -1}}{beta }}e^{-beta x^{2}},qquad xgeq 0,quad beta >1,}

    where the parameter β can be picked to minimize error on the desired interval of approximation.

  • Another approximation is given by Sergei Winitzki using his «global Padé approximations»:[19][20]: 2–3 
    {displaystyle operatorname {erf} xapprox operatorname {sgn} xcdot {sqrt {1-exp left(-x^{2}{frac {{frac {4}{pi }}+ax^{2}}{1+ax^{2}}}right)}}}

    where

    {displaystyle a={frac {8(pi -3)}{3pi (4-pi )}}approx 0.140012.}

    This is designed to be very accurate in a neighborhood of 0 and a neighborhood of infinity, and the relative error is less than 0.00035 for all real x. Using the alternate value a ≈ 0.147 reduces the maximum relative error to about 0.00013.[21]

    This approximation can be inverted to obtain an approximation for the inverse error function:

    {displaystyle operatorname {erf} ^{-1}xapprox operatorname {sgn} xcdot {sqrt {{sqrt {left({frac {2}{pi a}}+{frac {ln left(1-x^{2}right)}{2}}right)^{2}-{frac {ln left(1-x^{2}right)}{a}}}}-left({frac {2}{pi a}}+{frac {ln left(1-x^{2}right)}{2}}right)}}.}
  • An approximation with a maximal error of 1.2×10−7 for any real argument is:[22]
    {displaystyle operatorname {erf} x={begin{cases}1-tau &xgeq 0tau -1&x<0end{cases}}}

    with

    {displaystyle {begin{aligned}tau &=tcdot exp left(-x^{2}-1.26551223+1.00002368t+0.37409196t^{2}+0.09678418t^{3}-0.18628806t^{4}right.&left.qquad qquad qquad +0.27886807t^{5}-1.13520398t^{6}+1.48851587t^{7}-0.82215223t^{8}+0.17087277t^{9}right)end{aligned}}}

    and

    {displaystyle t={frac {1}{1+{frac {1}{2}}|x|}}.}

Table of values[edit]

x erf x 1 − erf x
0 0 1
0.02 0.022564575 0.977435425
0.04 0.045111106 0.954888894
0.06 0.067621594 0.932378406
0.08 0.090078126 0.909921874
0.1 0.112462916 0.887537084
0.2 0.222702589 0.777297411
0.3 0.328626759 0.671373241
0.4 0.428392355 0.571607645
0.5 0.520499878 0.479500122
0.6 0.603856091 0.396143909
0.7 0.677801194 0.322198806
0.8 0.742100965 0.257899035
0.9 0.796908212 0.203091788
1 0.842700793 0.157299207
1.1 0.880205070 0.119794930
1.2 0.910313978 0.089686022
1.3 0.934007945 0.065992055
1.4 0.952285120 0.047714880
1.5 0.966105146 0.033894854
1.6 0.976348383 0.023651617
1.7 0.983790459 0.016209541
1.8 0.989090502 0.010909498
1.9 0.992790429 0.007209571
2 0.995322265 0.004677735
2.1 0.997020533 0.002979467
2.2 0.998137154 0.001862846
2.3 0.998856823 0.001143177
2.4 0.999311486 0.000688514
2.5 0.999593048 0.000406952
3 0.999977910 0.000022090
3.5 0.999999257 0.000000743

[edit]

Complementary error function[edit]

The complementary error function, denoted erfc, is defined as

Plot of the complementary error function Erfc(z) in the complex plane from -2-2i to 2+2i with colors created with Mathematica 13.1 function ComplexPlot3D

Plot of the complementary error function Erfc(z) in the complex plane from -2-2i to 2+2i with colors created with Mathematica 13.1 function ComplexPlot3D

{displaystyle {begin{aligned}operatorname {erfc} x&=1-operatorname {erf} x[5pt]&={frac {2}{sqrt {pi }}}int _{x}^{infty }e^{-t^{2}},mathrm {d} t[5pt]&=e^{-x^{2}}operatorname {erfcx} x,end{aligned}}}

which also defines erfcx, the scaled complementary error function[23] (which can be used instead of erfc to avoid arithmetic underflow[23][24]). Another form of erfc x for x ≥ 0 is known as Craig’s formula, after its discoverer:[25]

{displaystyle operatorname {erfc} (xmid xgeq 0)={frac {2}{pi }}int _{0}^{frac {pi }{2}}exp left(-{frac {x^{2}}{sin ^{2}theta }}right),mathrm {d} theta .}

This expression is valid only for positive values of x, but it can be used in conjunction with erfc x = 2 − erfc(−x) to obtain erfc(x) for negative values. This form is advantageous in that the range of integration is fixed and finite. An extension of this expression for the erfc of the sum of two non-negative variables is as follows:[26]

{displaystyle operatorname {erfc} (x+ymid x,ygeq 0)={frac {2}{pi }}int _{0}^{frac {pi }{2}}exp left(-{frac {x^{2}}{sin ^{2}theta }}-{frac {y^{2}}{cos ^{2}theta }}right),mathrm {d} theta .}

Imaginary error function[edit]

The imaginary error function, denoted erfi, is defined as

Plot of the imaginary error function Erfi(z) in the complex plane from -2-2i to 2+2i with colors created with Mathematica 13.1 function ComplexPlot3D

Plot of the imaginary error function Erfi(z) in the complex plane from -2-2i to 2+2i with colors created with Mathematica 13.1 function ComplexPlot3D

{displaystyle {begin{aligned}operatorname {erfi} x&=-ioperatorname {erf} ix[5pt]&={frac {2}{sqrt {pi }}}int _{0}^{x}e^{t^{2}},mathrm {d} t[5pt]&={frac {2}{sqrt {pi }}}e^{x^{2}}D(x),end{aligned}}}

where D(x) is the Dawson function (which can be used instead of erfi to avoid arithmetic overflow[23]).

Despite the name «imaginary error function», erfi x is real when x is real.

When the error function is evaluated for arbitrary complex arguments z, the resulting complex error function is usually discussed in scaled form as the Faddeeva function:

w(z)=e^{-z^{2}}operatorname {erfc} (-iz)=operatorname {erfcx} (-iz).

Cumulative distribution function[edit]

The error function is essentially identical to the standard normal cumulative distribution function, denoted Φ, also named norm(x) by some software languages[citation needed], as they differ only by scaling and translation. Indeed,

the normal cumulative distribution function plotted in the complex plane

the normal cumulative distribution function plotted in the complex plane

{displaystyle {begin{aligned}Phi (x)&={frac {1}{sqrt {2pi }}}int _{-infty }^{x}e^{tfrac {-t^{2}}{2}},mathrm {d} t[6pt]&={frac {1}{2}}left(1+operatorname {erf} {frac {x}{sqrt {2}}}right)[6pt]&={frac {1}{2}}operatorname {erfc} left(-{frac {x}{sqrt {2}}}right)end{aligned}}}

or rearranged for erf and erfc:

{displaystyle {begin{aligned}operatorname {erf} (x)&=2Phi left(x{sqrt {2}}right)-1[6pt]operatorname {erfc} (x)&=2Phi left(-x{sqrt {2}}right)&=2left(1-Phi left(x{sqrt {2}}right)right).end{aligned}}}

Consequently, the error function is also closely related to the Q-function, which is the tail probability of the standard normal distribution. The Q-function can be expressed in terms of the error function as

{displaystyle {begin{aligned}Q(x)&={frac {1}{2}}-{frac {1}{2}}operatorname {erf} {frac {x}{sqrt {2}}}&={frac {1}{2}}operatorname {erfc} {frac {x}{sqrt {2}}}.end{aligned}}}

The inverse of Φ is known as the normal quantile function, or probit function and may be expressed in terms of the inverse error function as

{displaystyle operatorname {probit} (p)=Phi ^{-1}(p)={sqrt {2}}operatorname {erf} ^{-1}(2p-1)=-{sqrt {2}}operatorname {erfc} ^{-1}(2p).}

The standard normal cdf is used more often in probability and statistics, and the error function is used more often in other branches of mathematics.

The error function is a special case of the Mittag-Leffler function, and can also be expressed as a confluent hypergeometric function (Kummer’s function):

{displaystyle operatorname {erf} x={frac {2x}{sqrt {pi }}}Mleft({tfrac {1}{2}},{tfrac {3}{2}},-x^{2}right).}

It has a simple expression in terms of the Fresnel integral.[further explanation needed]

In terms of the regularized gamma function P and the incomplete gamma function,

{displaystyle operatorname {erf} x=operatorname {sgn} xcdot Pleft({tfrac {1}{2}},x^{2}right)={frac {operatorname {sgn} x}{sqrt {pi }}}gamma left({tfrac {1}{2}},x^{2}right).}

sgn x is the sign function.

Generalized error functions[edit]

Graph of generalised error functions En(x):
grey curve: E1(x) = 1 − ex/π
red curve: E2(x) = erf(x)
green curve: E3(x)
blue curve: E4(x)
gold curve: E5(x).

Some authors discuss the more general functions:[citation needed]

{displaystyle E_{n}(x)={frac {n!}{sqrt {pi }}}int _{0}^{x}e^{-t^{n}},mathrm {d} t={frac {n!}{sqrt {pi }}}sum _{p=0}^{infty }(-1)^{p}{frac {x^{np+1}}{(np+1)p!}}.}

Notable cases are:

  • E0(x) is a straight line through the origin: E0(x) = x/eπ
  • E2(x) is the error function, erf x.

After division by n!, all the En for odd n look similar (but not identical) to each other. Similarly, the En for even n look similar (but not identical) to each other after a simple division by n!. All generalised error functions for n > 0 look similar on the positive x side of the graph.

These generalised functions can equivalently be expressed for x > 0 using the gamma function and incomplete gamma function:

{displaystyle E_{n}(x)={frac {1}{sqrt {pi }}}Gamma (n)left(Gamma left({frac {1}{n}}right)-Gamma left({frac {1}{n}},x^{n}right)right),qquad x>0.}

Therefore, we can define the error function in terms of the incomplete gamma function:

{displaystyle operatorname {erf} x=1-{frac {1}{sqrt {pi }}}Gamma left({tfrac {1}{2}},x^{2}right).}

Iterated integrals of the complementary error function[edit]

The iterated integrals of the complementary error function are defined by[27]

{displaystyle {begin{aligned}operatorname {i} ^{n}!operatorname {erfc} z&=int _{z}^{infty }operatorname {i} ^{n-1}!operatorname {erfc} zeta ,mathrm {d} zeta [6pt]operatorname {i} ^{0}!operatorname {erfc} z&=operatorname {erfc} zoperatorname {i} ^{1}!operatorname {erfc} z&=operatorname {ierfc} z={frac {1}{sqrt {pi }}}e^{-z^{2}}-zoperatorname {erfc} zoperatorname {i} ^{2}!operatorname {erfc} z&={tfrac {1}{4}}left(operatorname {erfc} z-2zoperatorname {ierfc} zright)end{aligned}}}

The general recurrence formula is

{displaystyle 2ncdot operatorname {i} ^{n}!operatorname {erfc} z=operatorname {i} ^{n-2}!operatorname {erfc} z-2zcdot operatorname {i} ^{n-1}!operatorname {erfc} z}

They have the power series

{displaystyle operatorname {i} ^{n}!operatorname {erfc} z=sum _{j=0}^{infty }{frac {(-z)^{j}}{2^{n-j}j!,Gamma left(1+{frac {n-j}{2}}right)}},}

from which follow the symmetry properties

{displaystyle operatorname {i} ^{2m}!operatorname {erfc} (-z)=-operatorname {i} ^{2m}!operatorname {erfc} z+sum _{q=0}^{m}{frac {z^{2q}}{2^{2(m-q)-1}(2q)!(m-q)!}}}

and

{displaystyle operatorname {i} ^{2m+1}!operatorname {erfc} (-z)=operatorname {i} ^{2m+1}!operatorname {erfc} z+sum _{q=0}^{m}{frac {z^{2q+1}}{2^{2(m-q)-1}(2q+1)!(m-q)!}}.}

Implementations[edit]

As real function of a real argument[edit]

  • In Posix-compliant operating systems, the header math.h shall declare and the mathematical library libm shall provide the functions erf and erfc (double precision) as well as their single precision and extended precision counterparts erff, erfl and erfcf, erfcl.[28]
  • The GNU Scientific Library provides erf, erfc, log(erf), and scaled error functions.[29]

As complex function of a complex argument[edit]

  • libcerf, numeric C library for complex error functions, provides the complex functions cerf, cerfc, cerfcx and the real functions erfi, erfcx with approximately 13–14 digits precision, based on the Faddeeva function as implemented in the MIT Faddeeva Package

See also[edit]

[edit]

  • Gaussian integral, over the whole real line
  • Gaussian function, derivative
  • Dawson function, renormalized imaginary error function
  • Goodwin–Staton integral

In probability[edit]

  • Normal distribution
  • Normal cumulative distribution function, a scaled and shifted form of error function
  • Probit, the inverse or quantile function of the normal CDF
  • Q-function, the tail probability of the normal distribution

References[edit]

  1. ^ Andrews, Larry C. (1998). Special functions of mathematics for engineers. SPIE Press. p. 110. ISBN 9780819426161.
  2. ^ Glaisher, James Whitbread Lee (July 1871). «On a class of definite integrals». London, Edinburgh, and Dublin Philosophical Magazine and Journal of Science. 4. 42 (277): 294–302. doi:10.1080/14786447108640568. Retrieved 6 December 2017.
  3. ^ Glaisher, James Whitbread Lee (September 1871). «On a class of definite integrals. Part II». London, Edinburgh, and Dublin Philosophical Magazine and Journal of Science. 4. 42 (279): 421–436. doi:10.1080/14786447108640600. Retrieved 6 December 2017.
  4. ^ «A007680 – OEIS». oeis.org. Retrieved 2 April 2020.
  5. ^ Weisstein, Eric W. «Erf». MathWorld.
  6. ^ Schöpf, H. M.; Supancic, P. H. (2014). «On Bürmann’s Theorem and Its Application to Problems of Linear and Nonlinear Heat Transfer and Diffusion». The Mathematica Journal. 16. doi:10.3888/tmj.16-11.
  7. ^ Weisstein, Eric W. «Bürmann’s Theorem». MathWorld.
  8. ^ Bergsma, Wicher (2006). «On a new correlation coefficient, its orthogonal decomposition and associated tests of independence». arXiv:math/0604627.
  9. ^ Cuyt, Annie A. M.; Petersen, Vigdis B.; Verdonk, Brigitte; Waadeland, Haakon; Jones, William B. (2008). Handbook of Continued Fractions for Special Functions. Springer-Verlag. ISBN 978-1-4020-6948-2.
  10. ^ Ng, Edward W.; Geller, Murray (January 1969). «A table of integrals of the Error functions». Journal of Research of the National Bureau of Standards Section B. 73B (1): 1. doi:10.6028/jres.073B.001.
  11. ^ Schlömilch, Oskar Xavier (1859). «Ueber facultätenreihen». Zeitschrift für Mathematik und Physik (in German). 4: 390–415. Retrieved 4 December 2017.
  12. ^ Nielson, Niels (1906). Handbuch der Theorie der Gammafunktion (in German). Leipzig: B. G. Teubner. p. 283 Eq. 3. Retrieved 4 December 2017.
  13. ^ Chiani, M.; Dardari, D.; Simon, M.K. (2003). «New Exponential Bounds and Approximations for the Computation of Error Probability in Fading Channels» (PDF). IEEE Transactions on Wireless Communications. 2 (4): 840–845. CiteSeerX 10.1.1.190.6761. doi:10.1109/TWC.2003.814350.
  14. ^ Tanash, I.M.; Riihonen, T. (2020). «Global minimax approximations and bounds for the Gaussian Q-function by sums of exponentials». IEEE Transactions on Communications. 68 (10): 6514–6524. arXiv:2007.06939. doi:10.1109/TCOMM.2020.3006902. S2CID 220514754.
  15. ^ Tanash, I.M.; Riihonen, T. (2020). «Coefficients for Global Minimax Approximations and Bounds for the Gaussian Q-Function by Sums of Exponentials [Data set]». Zenodo. doi:10.5281/zenodo.4112978.
  16. ^ Karagiannidis, G. K.; Lioumpas, A. S. (2007). «An improved approximation for the Gaussian Q-function» (PDF). IEEE Communications Letters. 11 (8): 644–646. doi:10.1109/LCOMM.2007.070470. S2CID 4043576.
  17. ^ Tanash, I.M.; Riihonen, T. (2021). «Improved coefficients for the Karagiannidis–Lioumpas approximations and bounds to the Gaussian Q-function». IEEE Communications Letters. 25 (5): 1468–1471. arXiv:2101.07631. doi:10.1109/LCOMM.2021.3052257. S2CID 231639206.
  18. ^ Chang, Seok-Ho; Cosman, Pamela C.; Milstein, Laurence B. (November 2011). «Chernoff-Type Bounds for the Gaussian Error Function». IEEE Transactions on Communications. 59 (11): 2939–2944. doi:10.1109/TCOMM.2011.072011.100049. S2CID 13636638.
  19. ^ Winitzki, Sergei (2003). «Uniform approximations for transcendental functions». Computational Science and Its Applications – ICCSA 2003. Lecture Notes in Computer Science. Vol. 2667. Springer, Berlin. pp. 780–789. doi:10.1007/3-540-44839-X_82. ISBN 978-3-540-40155-1.
  20. ^ Zeng, Caibin; Chen, Yang Cuan (2015). «Global Padé approximations of the generalized Mittag-Leffler function and its inverse». Fractional Calculus and Applied Analysis. 18 (6): 1492–1506. arXiv:1310.5592. doi:10.1515/fca-2015-0086. S2CID 118148950. Indeed, Winitzki [32] provided the so-called global Padé approximation
  21. ^ Winitzki, Sergei (6 February 2008). «A handy approximation for the error function and its inverse».
  22. ^ Numerical Recipes in Fortran 77: The Art of Scientific Computing (ISBN 0-521-43064-X), 1992, page 214, Cambridge University Press.
  23. ^ a b c Cody, W. J. (March 1993), «Algorithm 715: SPECFUN—A portable FORTRAN package of special function routines and test drivers» (PDF), ACM Trans. Math. Softw., 19 (1): 22–32, CiteSeerX 10.1.1.643.4394, doi:10.1145/151271.151273, S2CID 5621105
  24. ^ Zaghloul, M. R. (1 March 2007), «On the calculation of the Voigt line profile: a single proper integral with a damped sine integrand», Monthly Notices of the Royal Astronomical Society, 375 (3): 1043–1048, Bibcode:2007MNRAS.375.1043Z, doi:10.1111/j.1365-2966.2006.11377.x
  25. ^ John W. Craig, A new, simple and exact result for calculating the probability of error for two-dimensional signal constellations Archived 3 April 2012 at the Wayback Machine, Proceedings of the 1991 IEEE Military Communication Conference, vol. 2, pp. 571–575.
  26. ^ Behnad, Aydin (2020). «A Novel Extension to Craig’s Q-Function Formula and Its Application in Dual-Branch EGC Performance Analysis». IEEE Transactions on Communications. 68 (7): 4117–4125. doi:10.1109/TCOMM.2020.2986209. S2CID 216500014.
  27. ^ Carslaw, H. S.; Jaeger, J. C. (1959), Conduction of Heat in Solids (2nd ed.), Oxford University Press, ISBN 978-0-19-853368-9, p 484
  28. ^ https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/math.h.html
  29. ^ «Special Functions – GSL 2.7 documentation».

Further reading[edit]

  • Abramowitz, Milton; Stegun, Irene Ann, eds. (1983) [June 1964]. «Chapter 7». Handbook of Mathematical Functions with Formulas, Graphs, and Mathematical Tables. Applied Mathematics Series. Vol. 55 (Ninth reprint with additional corrections of tenth original printing with corrections (December 1972); first ed.). Washington D.C.; New York: United States Department of Commerce, National Bureau of Standards; Dover Publications. p. 297. ISBN 978-0-486-61272-0. LCCN 64-60036. MR 0167642. LCCN 65-12253.
  • Press, William H.; Teukolsky, Saul A.; Vetterling, William T.; Flannery, Brian P. (2007), «Section 6.2. Incomplete Gamma Function and Error Function», Numerical Recipes: The Art of Scientific Computing (3rd ed.), New York: Cambridge University Press, ISBN 978-0-521-88068-8
  • Temme, Nico M. (2010), «Error Functions, Dawson’s and Fresnel Integrals», in Olver, Frank W. J.; Lozier, Daniel M.; Boisvert, Ronald F.; Clark, Charles W. (eds.), NIST Handbook of Mathematical Functions, Cambridge University Press, ISBN 978-0-521-19225-5, MR 2723248

External links[edit]

  • A Table of Integrals of the Error Functions
Error function
Plot of the error function

Plot of the error function

General information
General definition {displaystyle operatorname {erf} z={frac {2}{sqrt {pi }}}int _{0}^{z}e^{-t^{2}},mathrm {d} t}
Fields of application Probability, thermodynamics
Domain, Codomain and Image
Domain mathbb {C}
Image {displaystyle left(-1,1right)}
Basic features
Parity Odd
Specific features
Root 0
Derivative {displaystyle {frac {mathrm {d} }{mathrm {d} z}}operatorname {erf} z={frac {2}{sqrt {pi }}}e^{-z^{2}}}
Antiderivative {displaystyle int operatorname {erf} z,dz=zoperatorname {erf} z+{frac {e^{-z^{2}}}{sqrt {pi }}}+C}
Series definition
Taylor series {displaystyle operatorname {erf} z={frac {2}{sqrt {pi }}}sum _{n=0}^{infty }{frac {z}{2n+1}}prod _{k=1}^{n}{frac {-z^{2}}{k}}}

In mathematics, the error function (also called the Gauss error function), often denoted by erf, is a complex function of a complex variable defined as:[1]

{displaystyle operatorname {erf} z={frac {2}{sqrt {pi }}}int _{0}^{z}e^{-t^{2}},mathrm {d} t.}

This integral is a special (non-elementary) sigmoid function that occurs often in probability, statistics, and partial differential equations. In many of these applications, the function argument is a real number. If the function argument is real, then the function value is also real.

In statistics, for non-negative values of x, the error function has the following interpretation: for a random variable Y that is normally distributed with mean 0 and standard deviation 1/2, erf x is the probability that Y falls in the range [−x, x].

Two closely related functions are the complementary error function (erfc) defined as

{displaystyle operatorname {erfc} z=1-operatorname {erf} z,}

and the imaginary error function (erfi) defined as

{displaystyle operatorname {erfi} z=-ioperatorname {erf} iz,}

where i is the imaginary unit

Name[edit]

The name «error function» and its abbreviation erf were proposed by J. W. L. Glaisher in 1871 on account of its connection with «the theory of Probability, and notably the theory of Errors.»[2] The error function complement was also discussed by Glaisher in a separate publication in the same year.[3]
For the «law of facility» of errors whose density is given by

{displaystyle f(x)=left({frac {c}{pi }}right)^{frac {1}{2}}e^{-cx^{2}}}

(the normal distribution), Glaisher calculates the probability of an error lying between p and q as:

{displaystyle left({frac {c}{pi }}right)^{frac {1}{2}}int _{p}^{q}e^{-cx^{2}},mathrm {d} x={tfrac {1}{2}}left(operatorname {erf} left(q{sqrt {c}}right)-operatorname {erf} left(p{sqrt {c}}right)right).}

Plot of the error function Erf(z) in the complex plane from -2-2i to 2+2i with colors created with Mathematica 13.1 function ComplexPlot3D

Plot of the error function Erf(z) in the complex plane from -2-2i to 2+2i with colors created with Mathematica 13.1 function ComplexPlot3D

Applications[edit]

When the results of a series of measurements are described by a normal distribution with standard deviation σ and expected value 0, then erf (a/σ 2) is the probability that the error of a single measurement lies between a and +a, for positive a. This is useful, for example, in determining the bit error rate of a digital communication system.

The error and complementary error functions occur, for example, in solutions of the heat equation when boundary conditions are given by the Heaviside step function.

The error function and its approximations can be used to estimate results that hold with high probability or with low probability. Given a random variable X ~ Norm[μ,σ] (a normal distribution with mean μ and standard deviation σ) and a constant L < μ:

{displaystyle {begin{aligned}Pr[Xleq L]&={frac {1}{2}}+{frac {1}{2}}operatorname {erf} {frac {L-mu }{{sqrt {2}}sigma }}&approx Aexp left(-Bleft({frac {L-mu }{sigma }}right)^{2}right)end{aligned}}}

where A and B are certain numeric constants. If L is sufficiently far from the mean, specifically μLσln k, then:

{displaystyle Pr[Xleq L]leq Aexp(-Bln {k})={frac {A}{k^{B}}}}

so the probability goes to 0 as k → ∞.

The probability for X being in the interval [La, Lb] can be derived as

{displaystyle {begin{aligned}Pr[L_{a}leq Xleq L_{b}]&=int _{L_{a}}^{L_{b}}{frac {1}{{sqrt {2pi }}sigma }}exp left(-{frac {(x-mu )^{2}}{2sigma ^{2}}}right),mathrm {d} x&={frac {1}{2}}left(operatorname {erf} {frac {L_{b}-mu }{{sqrt {2}}sigma }}-operatorname {erf} {frac {L_{a}-mu }{{sqrt {2}}sigma }}right).end{aligned}}}

Properties[edit]

Integrand exp(−z2)

erf z

The property erf (−z) = −erf z means that the error function is an odd function. This directly results from the fact that the integrand et2 is an even function (the antiderivative of an even function which is zero at the origin is an odd function and vice versa).

Since the error function is an entire function which takes real numbers to real numbers, for any complex number z:

{displaystyle operatorname {erf} {overline {z}}={overline {operatorname {erf} z}}}

where z is the complex conjugate of z.

The integrand f = exp(−z2) and f = erf z are shown in the complex z-plane in the figures at right with domain coloring.

The error function at +∞ is exactly 1 (see Gaussian integral). At the real axis, erf z approaches unity at z → +∞ and −1 at z → −∞. At the imaginary axis, it tends to ±i.

Taylor series[edit]

The error function is an entire function; it has no singularities (except that at infinity) and its Taylor expansion always converges, but is famously known «[…] for its bad convergence if x > 1[4]

The defining integral cannot be evaluated in closed form in terms of elementary functions, but by expanding the integrand ez2 into its Maclaurin series and integrating term by term, one obtains the error function’s Maclaurin series as:

{displaystyle {begin{aligned}operatorname {erf} z&={frac {2}{sqrt {pi }}}sum _{n=0}^{infty }{frac {(-1)^{n}z^{2n+1}}{n!(2n+1)}}[6pt]&={frac {2}{sqrt {pi }}}left(z-{frac {z^{3}}{3}}+{frac {z^{5}}{10}}-{frac {z^{7}}{42}}+{frac {z^{9}}{216}}-cdots right)end{aligned}}}

which holds for every complex number z. The denominator terms are sequence A007680 in the OEIS.

For iterative calculation of the above series, the following alternative formulation may be useful:

{displaystyle {begin{aligned}operatorname {erf} z&={frac {2}{sqrt {pi }}}sum _{n=0}^{infty }left(zprod _{k=1}^{n}{frac {-(2k-1)z^{2}}{k(2k+1)}}right)[6pt]&={frac {2}{sqrt {pi }}}sum _{n=0}^{infty }{frac {z}{2n+1}}prod _{k=1}^{n}{frac {-z^{2}}{k}}end{aligned}}}

because −(2k − 1)z2/k(2k + 1) expresses the multiplier to turn the kth term into the (k + 1)th term (considering z as the first term).

The imaginary error function has a very similar Maclaurin series, which is:

{displaystyle {begin{aligned}operatorname {erfi} z&={frac {2}{sqrt {pi }}}sum _{n=0}^{infty }{frac {z^{2n+1}}{n!(2n+1)}}[6pt]&={frac {2}{sqrt {pi }}}left(z+{frac {z^{3}}{3}}+{frac {z^{5}}{10}}+{frac {z^{7}}{42}}+{frac {z^{9}}{216}}+cdots right)end{aligned}}}

which holds for every complex number z.

Derivative and integral[edit]

The derivative of the error function follows immediately from its definition:

{displaystyle {frac {mathrm {d} }{mathrm {d} z}}operatorname {erf} z={frac {2}{sqrt {pi }}}e^{-z^{2}}.}

From this, the derivative of the imaginary error function is also immediate:

{displaystyle {frac {d}{dz}}operatorname {erfi} z={frac {2}{sqrt {pi }}}e^{z^{2}}.}

An antiderivative of the error function, obtainable by integration by parts, is

{displaystyle zoperatorname {erf} z+{frac {e^{-z^{2}}}{sqrt {pi }}}.}

An antiderivative of the imaginary error function, also obtainable by integration by parts, is

{displaystyle zoperatorname {erfi} z-{frac {e^{z^{2}}}{sqrt {pi }}}.}

Higher order derivatives are given by

{displaystyle operatorname {erf} ^{(k)}z={frac {2(-1)^{k-1}}{sqrt {pi }}}{mathit {H}}_{k-1}(z)e^{-z^{2}}={frac {2}{sqrt {pi }}}{frac {mathrm {d} ^{k-1}}{mathrm {d} z^{k-1}}}left(e^{-z^{2}}right),qquad k=1,2,dots }

where H are the physicists’ Hermite polynomials.[5]

Bürmann series[edit]

An expansion,[6] which converges more rapidly for all real values of x than a Taylor expansion, is obtained by using Hans Heinrich Bürmann’s theorem:[7]

{displaystyle {begin{aligned}operatorname {erf} x&={frac {2}{sqrt {pi }}}operatorname {sgn} xcdot {sqrt {1-e^{-x^{2}}}}left(1-{frac {1}{12}}left(1-e^{-x^{2}}right)-{frac {7}{480}}left(1-e^{-x^{2}}right)^{2}-{frac {5}{896}}left(1-e^{-x^{2}}right)^{3}-{frac {787}{276480}}left(1-e^{-x^{2}}right)^{4}-cdots right)[10pt]&={frac {2}{sqrt {pi }}}operatorname {sgn} xcdot {sqrt {1-e^{-x^{2}}}}left({frac {sqrt {pi }}{2}}+sum _{k=1}^{infty }c_{k}e^{-kx^{2}}right).end{aligned}}}

where sgn is the sign function. By keeping only the first two coefficients and choosing c1 = 31/200 and c2 = −341/8000, the resulting approximation shows its largest relative error at x = ±1.3796, where it is less than 0.0036127:

{displaystyle operatorname {erf} xapprox {frac {2}{sqrt {pi }}}operatorname {sgn} xcdot {sqrt {1-e^{-x^{2}}}}left({frac {sqrt {pi }}{2}}+{frac {31}{200}}e^{-x^{2}}-{frac {341}{8000}}e^{-2x^{2}}right).}

Inverse functions[edit]

Given a complex number z, there is not a unique complex number w satisfying erf w = z, so a true inverse function would be multivalued. However, for −1 < x < 1, there is a unique real number denoted erf−1 x satisfying

{displaystyle operatorname {erf} left(operatorname {erf} ^{-1}xright)=x.}

The inverse error function is usually defined with domain (−1,1), and it is restricted to this domain in many computer algebra systems. However, it can be extended to the disk |z| < 1 of the complex plane, using the Maclaurin series

{displaystyle operatorname {erf} ^{-1}z=sum _{k=0}^{infty }{frac {c_{k}}{2k+1}}left({frac {sqrt {pi }}{2}}zright)^{2k+1},}

where c0 = 1 and

{displaystyle {begin{aligned}c_{k}&=sum _{m=0}^{k-1}{frac {c_{m}c_{k-1-m}}{(m+1)(2m+1)}}&=left{1,1,{frac {7}{6}},{frac {127}{90}},{frac {4369}{2520}},{frac {34807}{16200}},ldots right}.end{aligned}}}

So we have the series expansion (common factors have been canceled from numerators and denominators):

{displaystyle operatorname {erf} ^{-1}z={frac {sqrt {pi }}{2}}left(z+{frac {pi }{12}}z^{3}+{frac {7pi ^{2}}{480}}z^{5}+{frac {127pi ^{3}}{40320}}z^{7}+{frac {4369pi ^{4}}{5806080}}z^{9}+{frac {34807pi ^{5}}{182476800}}z^{11}+cdots right).}

(After cancellation the numerator/denominator fractions are entries OEIS: A092676/OEIS: A092677 in the OEIS; without cancellation the numerator terms are given in entry OEIS: A002067.) The error function’s value at ±∞ is equal to ±1.

For |z| < 1, we have erf(erf−1 z) = z.

The inverse complementary error function is defined as

{displaystyle operatorname {erfc} ^{-1}(1-z)=operatorname {erf} ^{-1}z.}

For real x, there is a unique real number erfi−1 x satisfying erfi(erfi−1 x) = x. The inverse imaginary error function is defined as erfi−1 x.[8]

For any real x, Newton’s method can be used to compute erfi−1 x, and for −1 ≤ x ≤ 1, the following Maclaurin series converges:

{displaystyle operatorname {erfi} ^{-1}z=sum _{k=0}^{infty }{frac {(-1)^{k}c_{k}}{2k+1}}left({frac {sqrt {pi }}{2}}zright)^{2k+1},}

where ck is defined as above.

Asymptotic expansion[edit]

A useful asymptotic expansion of the complementary error function (and therefore also of the error function) for large real x is

{displaystyle {begin{aligned}operatorname {erfc} x&={frac {e^{-x^{2}}}{x{sqrt {pi }}}}left(1+sum _{n=1}^{infty }(-1)^{n}{frac {1cdot 3cdot 5cdots (2n-1)}{left(2x^{2}right)^{n}}}right)[6pt]&={frac {e^{-x^{2}}}{x{sqrt {pi }}}}sum _{n=0}^{infty }(-1)^{n}{frac {(2n-1)!!}{left(2x^{2}right)^{n}}},end{aligned}}}

where (2n − 1)!! is the double factorial of (2n − 1), which is the product of all odd numbers up to (2n − 1). This series diverges for every finite x, and its meaning as asymptotic expansion is that for any integer N ≥ 1 one has

{displaystyle operatorname {erfc} x={frac {e^{-x^{2}}}{x{sqrt {pi }}}}sum _{n=0}^{N-1}(-1)^{n}{frac {(2n-1)!!}{left(2x^{2}right)^{n}}}+R_{N}(x)}

where the remainder, in Landau notation, is

{displaystyle R_{N}(x)=Oleft(x^{-(1+2N)}e^{-x^{2}}right)}

as x → ∞.

Indeed, the exact value of the remainder is

{displaystyle R_{N}(x):={frac {(-1)^{N}}{sqrt {pi }}}2^{1-2N}{frac {(2N)!}{N!}}int _{x}^{infty }t^{-2N}e^{-t^{2}},mathrm {d} t,}

which follows easily by induction, writing

{displaystyle e^{-t^{2}}=-(2t)^{-1}left(e^{-t^{2}}right)'}

and integrating by parts.

For large enough values of x, only the first few terms of this asymptotic expansion are needed to obtain a good approximation of erfc x (while for not too large values of x, the above Taylor expansion at 0 provides a very fast convergence).

Continued fraction expansion[edit]

A continued fraction expansion of the complementary error function is:[9]

{displaystyle operatorname {erfc} z={frac {z}{sqrt {pi }}}e^{-z^{2}}{cfrac {1}{z^{2}+{cfrac {a_{1}}{1+{cfrac {a_{2}}{z^{2}+{cfrac {a_{3}}{1+dotsb }}}}}}}},qquad a_{m}={frac {m}{2}}.}

Integral of error function with Gaussian density function[edit]

{displaystyle int _{-infty }^{infty }operatorname {erf} left(ax+bright){frac {1}{sqrt {2pi sigma ^{2}}}}exp left(-{frac {(x-mu )^{2}}{2sigma ^{2}}}right),mathrm {d} x=operatorname {erf} {frac {amu +b}{sqrt {1+2a^{2}sigma ^{2}}}},qquad a,b,mu ,sigma in mathbb {R} }

which appears related to Ng and Geller, formula 13 in section 4.3[10] with a change of variables.

Factorial series[edit]

The inverse factorial series:

{displaystyle {begin{aligned}operatorname {erfc} z&={frac {e^{-z^{2}}}{{sqrt {pi }},z}}sum _{n=0}^{infty }{frac {(-1)^{n}Q_{n}}{{(z^{2}+1)}^{bar {n}}}}&={frac {e^{-z^{2}}}{{sqrt {pi }},z}}left(1-{frac {1}{2}}{frac {1}{(z^{2}+1)}}+{frac {1}{4}}{frac {1}{(z^{2}+1)(z^{2}+2)}}-cdots right)end{aligned}}}

converges for Re(z2) > 0. Here

{displaystyle {begin{aligned}Q_{n}&{overset {text{def}}{{}={}}}{frac {1}{Gamma left({frac {1}{2}}right)}}int _{0}^{infty }tau (tau -1)cdots (tau -n+1)tau ^{-{frac {1}{2}}}e^{-tau },dtau &=sum _{k=0}^{n}left({tfrac {1}{2}}right)^{bar {k}}s(n,k),end{aligned}}}

zn denotes the rising factorial, and s(n,k) denotes a signed Stirling number of the first kind.[11][12]
There also exists a representation by an infinite sum containing the double factorial:

{displaystyle operatorname {erf} z={frac {2}{sqrt {pi }}}sum _{n=0}^{infty }{frac {(-2)^{n}(2n-1)!!}{(2n+1)!}}z^{2n+1}}

Numerical approximations[edit]

Approximation with elementary functions[edit]

  • Abramowitz and Stegun give several approximations of varying accuracy (equations 7.1.25–28). This allows one to choose the fastest approximation suitable for a given application. In order of increasing accuracy, they are:
    {displaystyle operatorname {erf} xapprox 1-{frac {1}{left(1+a_{1}x+a_{2}x^{2}+a_{3}x^{3}+a_{4}x^{4}right)^{4}}},qquad xgeq 0}

    (maximum error: 5×10−4)

    where a1 = 0.278393, a2 = 0.230389, a3 = 0.000972, a4 = 0.078108

    {displaystyle operatorname {erf} xapprox 1-left(a_{1}t+a_{2}t^{2}+a_{3}t^{3}right)e^{-x^{2}},quad t={frac {1}{1+px}},qquad xgeq 0}

    (maximum error: 2.5×10−5)

    where p = 0.47047, a1 = 0.3480242, a2 = −0.0958798, a3 = 0.7478556

    {displaystyle operatorname {erf} xapprox 1-{frac {1}{left(1+a_{1}x+a_{2}x^{2}+cdots +a_{6}x^{6}right)^{16}}},qquad xgeq 0}

    (maximum error: 3×10−7)

    where a1 = 0.0705230784, a2 = 0.0422820123, a3 = 0.0092705272, a4 = 0.0001520143, a5 = 0.0002765672, a6 = 0.0000430638

    {displaystyle operatorname {erf} xapprox 1-left(a_{1}t+a_{2}t^{2}+cdots +a_{5}t^{5}right)e^{-x^{2}},quad t={frac {1}{1+px}}}

    (maximum error: 1.5×10−7)

    where p = 0.3275911, a1 = 0.254829592, a2 = −0.284496736, a3 = 1.421413741, a4 = −1.453152027, a5 = 1.061405429

    All of these approximations are valid for x ≥ 0. To use these approximations for negative x, use the fact that erf x is an odd function, so erf x = −erf(−x).

  • Exponential bounds and a pure exponential approximation for the complementary error function are given by[13]
    {displaystyle {begin{aligned}operatorname {erfc} x&leq {tfrac {1}{2}}e^{-2x^{2}}+{tfrac {1}{2}}e^{-x^{2}}leq e^{-x^{2}},&quad x&>0operatorname {erfc} x&approx {tfrac {1}{6}}e^{-x^{2}}+{tfrac {1}{2}}e^{-{frac {4}{3}}x^{2}},&quad x&>0.end{aligned}}}
  • The above have been generalized to sums of N exponentials[14] with increasing accuracy in terms of N so that erfc x can be accurately approximated or bounded by 2(2x), where
    {displaystyle {tilde {Q}}(x)=sum _{n=1}^{N}a_{n}e^{-b_{n}x^{2}}.}

    In particular, there is a systematic methodology to solve the numerical coefficients {(an,bn)}N
    n = 1
    that yield a minimax approximation or bound for the closely related Q-function: Q(x) ≈ (x), Q(x) ≤ (x), or Q(x) ≥ (x) for x ≥ 0. The coefficients {(an,bn)}N
    n = 1
    for many variations of the exponential approximations and bounds up to N = 25 have been released to open access as a comprehensive dataset.[15]

  • A tight approximation of the complementary error function for x ∈ [0,∞) is given by Karagiannidis & Lioumpas (2007)[16] who showed for the appropriate choice of parameters {A,B} that
    {displaystyle operatorname {erfc} xapprox {frac {left(1-e^{-Ax}right)e^{-x^{2}}}{B{sqrt {pi }}x}}.}

    They determined {A,B} = {1.98,1.135}, which gave a good approximation for all x ≥ 0. Alternative coefficients are also available for tailoring accuracy for a specific application or transforming the expression into a tight bound.[17]

  • A single-term lower bound is[18]

    {displaystyle operatorname {erfc} xgeq {sqrt {frac {2e}{pi }}}{frac {sqrt {beta -1}}{beta }}e^{-beta x^{2}},qquad xgeq 0,quad beta >1,}

    where the parameter β can be picked to minimize error on the desired interval of approximation.

  • Another approximation is given by Sergei Winitzki using his «global Padé approximations»:[19][20]: 2–3 
    {displaystyle operatorname {erf} xapprox operatorname {sgn} xcdot {sqrt {1-exp left(-x^{2}{frac {{frac {4}{pi }}+ax^{2}}{1+ax^{2}}}right)}}}

    where

    {displaystyle a={frac {8(pi -3)}{3pi (4-pi )}}approx 0.140012.}

    This is designed to be very accurate in a neighborhood of 0 and a neighborhood of infinity, and the relative error is less than 0.00035 for all real x. Using the alternate value a ≈ 0.147 reduces the maximum relative error to about 0.00013.[21]

    This approximation can be inverted to obtain an approximation for the inverse error function:

    {displaystyle operatorname {erf} ^{-1}xapprox operatorname {sgn} xcdot {sqrt {{sqrt {left({frac {2}{pi a}}+{frac {ln left(1-x^{2}right)}{2}}right)^{2}-{frac {ln left(1-x^{2}right)}{a}}}}-left({frac {2}{pi a}}+{frac {ln left(1-x^{2}right)}{2}}right)}}.}
  • An approximation with a maximal error of 1.2×10−7 for any real argument is:[22]
    {displaystyle operatorname {erf} x={begin{cases}1-tau &xgeq 0tau -1&x<0end{cases}}}

    with

    {displaystyle {begin{aligned}tau &=tcdot exp left(-x^{2}-1.26551223+1.00002368t+0.37409196t^{2}+0.09678418t^{3}-0.18628806t^{4}right.&left.qquad qquad qquad +0.27886807t^{5}-1.13520398t^{6}+1.48851587t^{7}-0.82215223t^{8}+0.17087277t^{9}right)end{aligned}}}

    and

    {displaystyle t={frac {1}{1+{frac {1}{2}}|x|}}.}

Table of values[edit]

x erf x 1 − erf x
0 0 1
0.02 0.022564575 0.977435425
0.04 0.045111106 0.954888894
0.06 0.067621594 0.932378406
0.08 0.090078126 0.909921874
0.1 0.112462916 0.887537084
0.2 0.222702589 0.777297411
0.3 0.328626759 0.671373241
0.4 0.428392355 0.571607645
0.5 0.520499878 0.479500122
0.6 0.603856091 0.396143909
0.7 0.677801194 0.322198806
0.8 0.742100965 0.257899035
0.9 0.796908212 0.203091788
1 0.842700793 0.157299207
1.1 0.880205070 0.119794930
1.2 0.910313978 0.089686022
1.3 0.934007945 0.065992055
1.4 0.952285120 0.047714880
1.5 0.966105146 0.033894854
1.6 0.976348383 0.023651617
1.7 0.983790459 0.016209541
1.8 0.989090502 0.010909498
1.9 0.992790429 0.007209571
2 0.995322265 0.004677735
2.1 0.997020533 0.002979467
2.2 0.998137154 0.001862846
2.3 0.998856823 0.001143177
2.4 0.999311486 0.000688514
2.5 0.999593048 0.000406952
3 0.999977910 0.000022090
3.5 0.999999257 0.000000743

[edit]

Complementary error function[edit]

The complementary error function, denoted erfc, is defined as

Plot of the complementary error function Erfc(z) in the complex plane from -2-2i to 2+2i with colors created with Mathematica 13.1 function ComplexPlot3D

Plot of the complementary error function Erfc(z) in the complex plane from -2-2i to 2+2i with colors created with Mathematica 13.1 function ComplexPlot3D

{displaystyle {begin{aligned}operatorname {erfc} x&=1-operatorname {erf} x[5pt]&={frac {2}{sqrt {pi }}}int _{x}^{infty }e^{-t^{2}},mathrm {d} t[5pt]&=e^{-x^{2}}operatorname {erfcx} x,end{aligned}}}

which also defines erfcx, the scaled complementary error function[23] (which can be used instead of erfc to avoid arithmetic underflow[23][24]). Another form of erfc x for x ≥ 0 is known as Craig’s formula, after its discoverer:[25]

{displaystyle operatorname {erfc} (xmid xgeq 0)={frac {2}{pi }}int _{0}^{frac {pi }{2}}exp left(-{frac {x^{2}}{sin ^{2}theta }}right),mathrm {d} theta .}

This expression is valid only for positive values of x, but it can be used in conjunction with erfc x = 2 − erfc(−x) to obtain erfc(x) for negative values. This form is advantageous in that the range of integration is fixed and finite. An extension of this expression for the erfc of the sum of two non-negative variables is as follows:[26]

{displaystyle operatorname {erfc} (x+ymid x,ygeq 0)={frac {2}{pi }}int _{0}^{frac {pi }{2}}exp left(-{frac {x^{2}}{sin ^{2}theta }}-{frac {y^{2}}{cos ^{2}theta }}right),mathrm {d} theta .}

Imaginary error function[edit]

The imaginary error function, denoted erfi, is defined as

Plot of the imaginary error function Erfi(z) in the complex plane from -2-2i to 2+2i with colors created with Mathematica 13.1 function ComplexPlot3D

Plot of the imaginary error function Erfi(z) in the complex plane from -2-2i to 2+2i with colors created with Mathematica 13.1 function ComplexPlot3D

{displaystyle {begin{aligned}operatorname {erfi} x&=-ioperatorname {erf} ix[5pt]&={frac {2}{sqrt {pi }}}int _{0}^{x}e^{t^{2}},mathrm {d} t[5pt]&={frac {2}{sqrt {pi }}}e^{x^{2}}D(x),end{aligned}}}

where D(x) is the Dawson function (which can be used instead of erfi to avoid arithmetic overflow[23]).

Despite the name «imaginary error function», erfi x is real when x is real.

When the error function is evaluated for arbitrary complex arguments z, the resulting complex error function is usually discussed in scaled form as the Faddeeva function:

w(z)=e^{-z^{2}}operatorname {erfc} (-iz)=operatorname {erfcx} (-iz).

Cumulative distribution function[edit]

The error function is essentially identical to the standard normal cumulative distribution function, denoted Φ, also named norm(x) by some software languages[citation needed], as they differ only by scaling and translation. Indeed,

the normal cumulative distribution function plotted in the complex plane

the normal cumulative distribution function plotted in the complex plane

{displaystyle {begin{aligned}Phi (x)&={frac {1}{sqrt {2pi }}}int _{-infty }^{x}e^{tfrac {-t^{2}}{2}},mathrm {d} t[6pt]&={frac {1}{2}}left(1+operatorname {erf} {frac {x}{sqrt {2}}}right)[6pt]&={frac {1}{2}}operatorname {erfc} left(-{frac {x}{sqrt {2}}}right)end{aligned}}}

or rearranged for erf and erfc:

{displaystyle {begin{aligned}operatorname {erf} (x)&=2Phi left(x{sqrt {2}}right)-1[6pt]operatorname {erfc} (x)&=2Phi left(-x{sqrt {2}}right)&=2left(1-Phi left(x{sqrt {2}}right)right).end{aligned}}}

Consequently, the error function is also closely related to the Q-function, which is the tail probability of the standard normal distribution. The Q-function can be expressed in terms of the error function as

{displaystyle {begin{aligned}Q(x)&={frac {1}{2}}-{frac {1}{2}}operatorname {erf} {frac {x}{sqrt {2}}}&={frac {1}{2}}operatorname {erfc} {frac {x}{sqrt {2}}}.end{aligned}}}

The inverse of Φ is known as the normal quantile function, or probit function and may be expressed in terms of the inverse error function as

{displaystyle operatorname {probit} (p)=Phi ^{-1}(p)={sqrt {2}}operatorname {erf} ^{-1}(2p-1)=-{sqrt {2}}operatorname {erfc} ^{-1}(2p).}

The standard normal cdf is used more often in probability and statistics, and the error function is used more often in other branches of mathematics.

The error function is a special case of the Mittag-Leffler function, and can also be expressed as a confluent hypergeometric function (Kummer’s function):

{displaystyle operatorname {erf} x={frac {2x}{sqrt {pi }}}Mleft({tfrac {1}{2}},{tfrac {3}{2}},-x^{2}right).}

It has a simple expression in terms of the Fresnel integral.[further explanation needed]

In terms of the regularized gamma function P and the incomplete gamma function,

{displaystyle operatorname {erf} x=operatorname {sgn} xcdot Pleft({tfrac {1}{2}},x^{2}right)={frac {operatorname {sgn} x}{sqrt {pi }}}gamma left({tfrac {1}{2}},x^{2}right).}

sgn x is the sign function.

Generalized error functions[edit]

Graph of generalised error functions En(x):
grey curve: E1(x) = 1 − ex/π
red curve: E2(x) = erf(x)
green curve: E3(x)
blue curve: E4(x)
gold curve: E5(x).

Some authors discuss the more general functions:[citation needed]

{displaystyle E_{n}(x)={frac {n!}{sqrt {pi }}}int _{0}^{x}e^{-t^{n}},mathrm {d} t={frac {n!}{sqrt {pi }}}sum _{p=0}^{infty }(-1)^{p}{frac {x^{np+1}}{(np+1)p!}}.}

Notable cases are:

  • E0(x) is a straight line through the origin: E0(x) = x/eπ
  • E2(x) is the error function, erf x.

After division by n!, all the En for odd n look similar (but not identical) to each other. Similarly, the En for even n look similar (but not identical) to each other after a simple division by n!. All generalised error functions for n > 0 look similar on the positive x side of the graph.

These generalised functions can equivalently be expressed for x > 0 using the gamma function and incomplete gamma function:

{displaystyle E_{n}(x)={frac {1}{sqrt {pi }}}Gamma (n)left(Gamma left({frac {1}{n}}right)-Gamma left({frac {1}{n}},x^{n}right)right),qquad x>0.}

Therefore, we can define the error function in terms of the incomplete gamma function:

{displaystyle operatorname {erf} x=1-{frac {1}{sqrt {pi }}}Gamma left({tfrac {1}{2}},x^{2}right).}

Iterated integrals of the complementary error function[edit]

The iterated integrals of the complementary error function are defined by[27]

{displaystyle {begin{aligned}operatorname {i} ^{n}!operatorname {erfc} z&=int _{z}^{infty }operatorname {i} ^{n-1}!operatorname {erfc} zeta ,mathrm {d} zeta [6pt]operatorname {i} ^{0}!operatorname {erfc} z&=operatorname {erfc} zoperatorname {i} ^{1}!operatorname {erfc} z&=operatorname {ierfc} z={frac {1}{sqrt {pi }}}e^{-z^{2}}-zoperatorname {erfc} zoperatorname {i} ^{2}!operatorname {erfc} z&={tfrac {1}{4}}left(operatorname {erfc} z-2zoperatorname {ierfc} zright)end{aligned}}}

The general recurrence formula is

{displaystyle 2ncdot operatorname {i} ^{n}!operatorname {erfc} z=operatorname {i} ^{n-2}!operatorname {erfc} z-2zcdot operatorname {i} ^{n-1}!operatorname {erfc} z}

They have the power series

{displaystyle operatorname {i} ^{n}!operatorname {erfc} z=sum _{j=0}^{infty }{frac {(-z)^{j}}{2^{n-j}j!,Gamma left(1+{frac {n-j}{2}}right)}},}

from which follow the symmetry properties

{displaystyle operatorname {i} ^{2m}!operatorname {erfc} (-z)=-operatorname {i} ^{2m}!operatorname {erfc} z+sum _{q=0}^{m}{frac {z^{2q}}{2^{2(m-q)-1}(2q)!(m-q)!}}}

and

{displaystyle operatorname {i} ^{2m+1}!operatorname {erfc} (-z)=operatorname {i} ^{2m+1}!operatorname {erfc} z+sum _{q=0}^{m}{frac {z^{2q+1}}{2^{2(m-q)-1}(2q+1)!(m-q)!}}.}

Implementations[edit]

As real function of a real argument[edit]

  • In Posix-compliant operating systems, the header math.h shall declare and the mathematical library libm shall provide the functions erf and erfc (double precision) as well as their single precision and extended precision counterparts erff, erfl and erfcf, erfcl.[28]
  • The GNU Scientific Library provides erf, erfc, log(erf), and scaled error functions.[29]

As complex function of a complex argument[edit]

  • libcerf, numeric C library for complex error functions, provides the complex functions cerf, cerfc, cerfcx and the real functions erfi, erfcx with approximately 13–14 digits precision, based on the Faddeeva function as implemented in the MIT Faddeeva Package

See also[edit]

[edit]

  • Gaussian integral, over the whole real line
  • Gaussian function, derivative
  • Dawson function, renormalized imaginary error function
  • Goodwin–Staton integral

In probability[edit]

  • Normal distribution
  • Normal cumulative distribution function, a scaled and shifted form of error function
  • Probit, the inverse or quantile function of the normal CDF
  • Q-function, the tail probability of the normal distribution

References[edit]

  1. ^ Andrews, Larry C. (1998). Special functions of mathematics for engineers. SPIE Press. p. 110. ISBN 9780819426161.
  2. ^ Glaisher, James Whitbread Lee (July 1871). «On a class of definite integrals». London, Edinburgh, and Dublin Philosophical Magazine and Journal of Science. 4. 42 (277): 294–302. doi:10.1080/14786447108640568. Retrieved 6 December 2017.
  3. ^ Glaisher, James Whitbread Lee (September 1871). «On a class of definite integrals. Part II». London, Edinburgh, and Dublin Philosophical Magazine and Journal of Science. 4. 42 (279): 421–436. doi:10.1080/14786447108640600. Retrieved 6 December 2017.
  4. ^ «A007680 – OEIS». oeis.org. Retrieved 2 April 2020.
  5. ^ Weisstein, Eric W. «Erf». MathWorld.
  6. ^ Schöpf, H. M.; Supancic, P. H. (2014). «On Bürmann’s Theorem and Its Application to Problems of Linear and Nonlinear Heat Transfer and Diffusion». The Mathematica Journal. 16. doi:10.3888/tmj.16-11.
  7. ^ Weisstein, Eric W. «Bürmann’s Theorem». MathWorld.
  8. ^ Bergsma, Wicher (2006). «On a new correlation coefficient, its orthogonal decomposition and associated tests of independence». arXiv:math/0604627.
  9. ^ Cuyt, Annie A. M.; Petersen, Vigdis B.; Verdonk, Brigitte; Waadeland, Haakon; Jones, William B. (2008). Handbook of Continued Fractions for Special Functions. Springer-Verlag. ISBN 978-1-4020-6948-2.
  10. ^ Ng, Edward W.; Geller, Murray (January 1969). «A table of integrals of the Error functions». Journal of Research of the National Bureau of Standards Section B. 73B (1): 1. doi:10.6028/jres.073B.001.
  11. ^ Schlömilch, Oskar Xavier (1859). «Ueber facultätenreihen». Zeitschrift für Mathematik und Physik (in German). 4: 390–415. Retrieved 4 December 2017.
  12. ^ Nielson, Niels (1906). Handbuch der Theorie der Gammafunktion (in German). Leipzig: B. G. Teubner. p. 283 Eq. 3. Retrieved 4 December 2017.
  13. ^ Chiani, M.; Dardari, D.; Simon, M.K. (2003). «New Exponential Bounds and Approximations for the Computation of Error Probability in Fading Channels» (PDF). IEEE Transactions on Wireless Communications. 2 (4): 840–845. CiteSeerX 10.1.1.190.6761. doi:10.1109/TWC.2003.814350.
  14. ^ Tanash, I.M.; Riihonen, T. (2020). «Global minimax approximations and bounds for the Gaussian Q-function by sums of exponentials». IEEE Transactions on Communications. 68 (10): 6514–6524. arXiv:2007.06939. doi:10.1109/TCOMM.2020.3006902. S2CID 220514754.
  15. ^ Tanash, I.M.; Riihonen, T. (2020). «Coefficients for Global Minimax Approximations and Bounds for the Gaussian Q-Function by Sums of Exponentials [Data set]». Zenodo. doi:10.5281/zenodo.4112978.
  16. ^ Karagiannidis, G. K.; Lioumpas, A. S. (2007). «An improved approximation for the Gaussian Q-function» (PDF). IEEE Communications Letters. 11 (8): 644–646. doi:10.1109/LCOMM.2007.070470. S2CID 4043576.
  17. ^ Tanash, I.M.; Riihonen, T. (2021). «Improved coefficients for the Karagiannidis–Lioumpas approximations and bounds to the Gaussian Q-function». IEEE Communications Letters. 25 (5): 1468–1471. arXiv:2101.07631. doi:10.1109/LCOMM.2021.3052257. S2CID 231639206.
  18. ^ Chang, Seok-Ho; Cosman, Pamela C.; Milstein, Laurence B. (November 2011). «Chernoff-Type Bounds for the Gaussian Error Function». IEEE Transactions on Communications. 59 (11): 2939–2944. doi:10.1109/TCOMM.2011.072011.100049. S2CID 13636638.
  19. ^ Winitzki, Sergei (2003). «Uniform approximations for transcendental functions». Computational Science and Its Applications – ICCSA 2003. Lecture Notes in Computer Science. Vol. 2667. Springer, Berlin. pp. 780–789. doi:10.1007/3-540-44839-X_82. ISBN 978-3-540-40155-1.
  20. ^ Zeng, Caibin; Chen, Yang Cuan (2015). «Global Padé approximations of the generalized Mittag-Leffler function and its inverse». Fractional Calculus and Applied Analysis. 18 (6): 1492–1506. arXiv:1310.5592. doi:10.1515/fca-2015-0086. S2CID 118148950. Indeed, Winitzki [32] provided the so-called global Padé approximation
  21. ^ Winitzki, Sergei (6 February 2008). «A handy approximation for the error function and its inverse».
  22. ^ Numerical Recipes in Fortran 77: The Art of Scientific Computing (ISBN 0-521-43064-X), 1992, page 214, Cambridge University Press.
  23. ^ a b c Cody, W. J. (March 1993), «Algorithm 715: SPECFUN—A portable FORTRAN package of special function routines and test drivers» (PDF), ACM Trans. Math. Softw., 19 (1): 22–32, CiteSeerX 10.1.1.643.4394, doi:10.1145/151271.151273, S2CID 5621105
  24. ^ Zaghloul, M. R. (1 March 2007), «On the calculation of the Voigt line profile: a single proper integral with a damped sine integrand», Monthly Notices of the Royal Astronomical Society, 375 (3): 1043–1048, Bibcode:2007MNRAS.375.1043Z, doi:10.1111/j.1365-2966.2006.11377.x
  25. ^ John W. Craig, A new, simple and exact result for calculating the probability of error for two-dimensional signal constellations Archived 3 April 2012 at the Wayback Machine, Proceedings of the 1991 IEEE Military Communication Conference, vol. 2, pp. 571–575.
  26. ^ Behnad, Aydin (2020). «A Novel Extension to Craig’s Q-Function Formula and Its Application in Dual-Branch EGC Performance Analysis». IEEE Transactions on Communications. 68 (7): 4117–4125. doi:10.1109/TCOMM.2020.2986209. S2CID 216500014.
  27. ^ Carslaw, H. S.; Jaeger, J. C. (1959), Conduction of Heat in Solids (2nd ed.), Oxford University Press, ISBN 978-0-19-853368-9, p 484
  28. ^ https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/math.h.html
  29. ^ «Special Functions – GSL 2.7 documentation».

Further reading[edit]

  • Abramowitz, Milton; Stegun, Irene Ann, eds. (1983) [June 1964]. «Chapter 7». Handbook of Mathematical Functions with Formulas, Graphs, and Mathematical Tables. Applied Mathematics Series. Vol. 55 (Ninth reprint with additional corrections of tenth original printing with corrections (December 1972); first ed.). Washington D.C.; New York: United States Department of Commerce, National Bureau of Standards; Dover Publications. p. 297. ISBN 978-0-486-61272-0. LCCN 64-60036. MR 0167642. LCCN 65-12253.
  • Press, William H.; Teukolsky, Saul A.; Vetterling, William T.; Flannery, Brian P. (2007), «Section 6.2. Incomplete Gamma Function and Error Function», Numerical Recipes: The Art of Scientific Computing (3rd ed.), New York: Cambridge University Press, ISBN 978-0-521-88068-8
  • Temme, Nico M. (2010), «Error Functions, Dawson’s and Fresnel Integrals», in Olver, Frank W. J.; Lozier, Daniel M.; Boisvert, Ronald F.; Clark, Charles W. (eds.), NIST Handbook of Mathematical Functions, Cambridge University Press, ISBN 978-0-521-19225-5, MR 2723248

External links[edit]

  • A Table of Integrals of the Error Functions

Найдем вероятность попадания случайной величины, распределенной по нормальному закону, в заданный интервал.

Обозначим

Тогда

Т. к. интеграл не выражается через элементарные функции, то вводится в рассмотрение функция

,

Которая называется Функцией Лапласа Или Интегралом вероятностей.

Значения этой функции при различных значениях Х посчитаны и приводятся в специальных таблицах.

Ниже показан график функции Лапласа.

Функция Лапласа обладает следующими свойствами:

1) Ф(0) = 0;

2) Ф(-Х) = — Ф(Х);

3) Ф(¥) = 1.

Функцию Лапласа также называют Функцией ошибок и обозначают erf X.

Еще используется Нормированная Функция Лапласа, которая связана с функцией Лапласа соотношением:

Ниже показан график нормированной функции Лапласа.

При рассмотрении нормального закона распределения выделяется важный частный случай, известный как Правило трех сигм.

Запишем вероятность того, что отклонение нормально распределенной случайной величины от математического ожидания меньше заданной величины D:

Если принять D = 3s, то получаем с использованием таблиц значений функции Лапласа:

Т. е. вероятность того, что случайная величина отклонится от своего математического ожидание на величину, большую чем утроенное среднее квадратичное отклонение, практически равна нулю.

Это правило называется Правилом трех сигм.

Не практике считается, что если для какой – либо случайной величины выполняется правило трех сигм, то эта случайная величина имеет нормальное распределение.

Пример. Поезд состоит из 100 вагонов. Масса каждого вагона – случайная величина, распределенная по нормальному закону с математическим ожидание А = 65 т и средним квадратичным отклонением s = 0,9 т. Локомотив может везти состав массой не более 6600 т, в противном случае необходимо прицеплять второй локомотив. Найти вероятность того, что второй локомотив не потребуется.

Второй локомотив не потребуется, если отклонение массы состава от ожидаемого (100×65 = 6500) не превосходит 6600 – 6500 = 100 т.

Т. к. масса каждого вагона имеет нормальное распределение, то и масса всего состава тоже будет распределена нормально.

Получаем:

Пример. Нормально распределенная случайная величина Х задана своими параметрами – А =2 – Математическое ожидание и s = 1 – среднее квадратическое отклонение. Требуется написать плотность вероятности и построить ее график, найти вероятность того, Х примет значение из интервала (1; 3), найти вероятность того, что Х отклонится (по модулю) от математического ожидания не более чем на 2.

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

Построим график:

Найдем вероятность попадания случайной величины в интервал (1; 3).

Найдем вероятность отклонение случайной величины от математического ожидания на величину, не большую чем 2.

Тот же результат может быть получен с использованием нормированной функции Лапласа.

< Предыдущая   Следующая >

How can I calculate the value of this integral:

enter image description here

f_tu(t) is given as numpy.array. The graph looks like this:

enter image description here

How can I implement this?
Everything I could find looks something like this

from scipy.integrate import quad
def f(x):
    return 1/sin(x)
I = quad(f, 0, 1)

but I have an array there, not a specific function like sin.

asked Oct 31, 2020 at 0:57

RoyalGoose's user avatar

2

How about auc from sklearn.metrics?

import numpy as np

import numpy as np

from scipy.integrate import quad

from sklearn.metrics import auc

x = np.arange(0, 100, 0.001)
y = np.sin(x)

print('auc:', auc(x,y))

print('quad:', quad(np.sin, 0, 100))

auc: 0.13818791291277366
quad: (0.1376811277123232, 9.459751315610276e-09)

answered Oct 31, 2020 at 1:04

Marcin's user avatar

MarcinMarcin

1,3117 silver badges15 bronze badges

2

Okay, so you have one of those pesky infinity integrals. Here is how I would deal with it:

import numpy as np
from scipy.integrate import quad

def f(x):
return(1/(x**2)) #put your function to integrate here

print(quad(f,0,np.Infinity)) #integrates from 0 to infinity

This returns two values. The first is the estimated value of the integral, and the second is the approximate absolute error of the integral which is useful to know.

answered Oct 31, 2020 at 1:28

SpencerLS's user avatar

SpencerLSSpencerLS

3624 silver badges16 bronze badges

4

If you want to integrate a numpy array here is a simple solution:

import numpy as np

print(np.trapz(your numpy array here))

answered Oct 31, 2020 at 1:49

SpencerLS's user avatar

SpencerLSSpencerLS

3624 silver badges16 bronze badges

0

Метод получения интеграла в модуле Scipy на Python:

SciPy реализует базовое использование функции, чтобы найти интеграл функции, интеграл, продвинутая математика имеет много разговоров, основной смысл — найти площадь под кривой.

Среди них rn можно рассматривать как отклонение, которым обычно можно пренебречь, а wi можно рассматривать как вес.

SciPy предоставляет множество функций для вычисления различных типов интегралов, которые можно разделить на две категории в зависимости от разницы входных параметров: одна — это вход известной функции и верхний и нижний пределы интеграла; другая — набор входных точек.Это применимо к некоторым данным, собранным после физической реализации, но функция не может быть определена, но есть много точек данных, тогда какая площадь под огибающей этих точек также является интегральной проблемой, поэтому существует точка, установленная в функции SciPy Integral, параметр функции — это массив или список в форме.

1. Интеграл с известным типом функции

В этом разделе показано, как вычислить интеграл в SciPy в виде нескольких вопросов.

  • Вопрос 1:Здесь предположим, что функцияf (x) = x + 1, верхний и нижний пределы интеграла равны[1,2] математическое выражение:

Вы можете использовать подмодуль, интегрированный в модуль Scipyчетырехъядерная функцияНайти расчетное значение этой математической задачи.

from scipy import integrate
def f(x):
    return x + 1
v, err = integrate.quad(f, 1, 2)
print v

Результат выполнения программы:

2.5

Вопрос 2:Но для функции f (x) = ax + b, можно ли использовать функцию quad, если a и b могут быть неизвестны? Ответ - да, quad имеет формальный параметр args, который можно передавать в некоторых параметрах.

from scipy import integrate
def f(x, a, b):
    return a * x + b
v, err = integrate.quad(f, 1, 2, args = (-1, 1))
print v

Результат выполнения программы:

-0.5

Вопрос 3:Если вы встретите точку останова в интегральной функции, вы можете использовать точки функции quad, чтобы задать точку останова и продолжить интегрирование. Например:


Вотf (x) вЕсть точка останова, где x = 0, если точка останова не указана, она будет вычислена путем вычисления квадратов:
from scipy import integrate
import numpy as np
def f(x):
    return 1 / np.sqrt(abs(x))
v, err = integrate.quad(f, -1, 1)
print v

Когда программа запущена:

scipy1801.py:4: RuntimeWarning: divide by zero encountered in double_scalars
  return 1 / np.sqrt(abs(x))
inf

Результат — бесконечность (бесконечность, бесконечность) и есть ошибка деления на 0! немного отредактируйте:

from scipy import integrate
import numpy as np
def f(x):
    return 1 / np.sqrt(abs(x))
v, err = integrate.quad(f, -1, 1, points=[0])
print v

оказаться:

4

Мы можем нарисовать визуальную кривую этой функции:

from scipy import integrate
import numpy as np
def f(x):
    return 1 / np.sqrt(abs(x))
v, err = integrate.quad(f, -1, 1, points=[0])
print v

import numpy as np, matplotlib.pyplot as plt
from mpl_toolkits.mplot3d.axes3d import Axes3D
fig, ax = plt.subplots(figsize=(8, 3))
x = np.linspace(-1, 1, 10000)
ax.plot(x, f(x), lw=2)
ax.fill_between(x, f(x), color=‘green’, alpha=0.5)
ax.set_xlabel(«

x

x

«, fontsize=18)
ax.set_ylabel(«

f

(

x

)

f(x)

«, fontsize=18)
ax.set_ylim(0, 25)
plt.show()

Получите следующую таблицу результатов:

2 Дайте интеграл от множества точек

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

  • Вопрос 4ИнтегрироватьНо есть 10 примеров данных этой функции, функция quad неf (x) = x, но соответствующие(xi,yi)。
from scipy import integrate
import numpy as np
def f(x):
    return np.sqrt(x)
x = np.linspace(0, 2, 10)
y = f(x)
v = integrate.trapz(y, x)
print v

Результаты программы:

1.8652953655957172

3 Несколько точек

Двойной интеграл в SciPy можно вычислить с помощью функции dblquad, а тройной интеграл можно вычислить с помощью функции tplquad.Функцию nquad можно использовать для множественных интегралов от f (x1, x2, …, xn).

  • Двойная интегральная функция dblquad для вычисления, предположим, что есть функцияf (x, y) необходимо вычислить свой двойной интеграл.
Как использовать Scipyфункция dblquadКакая? Общий формат выражения для универсального двойного интеграла:

Тогда первый параметр функции dblquad должен бытьf (x, y), второй, третий, четвертый и пятый - это a, b, g (x), h (x), что означает, что четвертая и пятая функции dblquad являются функцией.
from scipy import integrate
import numpy as np
def f(x, y):
    return x * y
def h(x):
    return x
v, err = integrate.dblquad(f, 1, 2, lambda x: 1, h)
print v

Результат выполнения программы:

1.125

Тройной интеграл можно вычислить с помощью tplquad. Общий формат выражения тройного интеграла:

  • ифункция tplquadФорма вызова:
tqlquad(f, a, b, g, h, q, r)

Среди них все функции f, g, h, q и r. Ниже для расчета

Программа, написанная на Python, выглядит так:

from scipy import integrate
import numpy as np
f = lambda x, y, z : x
g = lambda x : 0
h = lambda x : (1 - x) / 2
q = lambda x, y : 0
r = lambda x, y : 1 - x - 2 * y 
v, err = integrate.tplquad(f, 0, 1, g, h, q, r)
print v

Результаты выполнения программы:

0.02083333333

 

Integration (:mod:`scipy.integrate`)

.. sectionauthor:: Travis E. Oliphant

.. currentmodule:: scipy.integrate

The :mod:`scipy.integrate` sub-package provides several integration
techniques including an ordinary differential equation integrator. An
overview of the module is provided by the help command:

.. literalinclude:: examples/4-1


General integration (:func:`quad`)

The function :obj:`quad` is provided to integrate a function of one
variable between two points. The points can be pminfty
(pm inf) to indicate infinite limits. For example,
suppose you wish to integrate a bessel function jv(2.5, x) along
the interval [0, 4.5].

I=int_{0}^{4.5}J_{2.5}left(xright), dx.

This could be computed using :obj:`quad`:

>>> import scipy.integrate as integrate
>>> import scipy.special as special
>>> result = integrate.quad(lambda x: special.jv(2.5,x), 0, 4.5)
>>> result
(1.1178179380783249, 7.8663172481899801e-09)
>>> from numpy import sqrt, sin, cos, pi
>>> I = sqrt(2/pi)*(18.0/27*sqrt(2)*cos(4.5) - 4.0/27*sqrt(2)*sin(4.5) +
...                 sqrt(2*pi) * special.fresnel(3/sqrt(pi))[0])
>>> I
1.117817938088701
>>> print(abs(result[0]-I))
1.03761443881e-11

The first argument to quad is a «callable» Python object (i.e., a
function, method, or class instance). Notice the use of a lambda-
function in this case as the argument. The next two arguments are the
limits of integration. The return value is a tuple, with the first
element holding the estimated value of the integral and the second
element holding an upper bound on the error. Notice, that in this
case, the true value of this integral is

I=sqrt{frac{2}{pi}}left(frac{18}{27}sqrt{2}cosleft(4.5right)-frac{4}{27}sqrt{2}sinleft(4.5right)+sqrt{2pi}textrm{Si}left(frac{3}{sqrt{pi}}right)right),

where

textrm{Si}left(xright)=int_{0}^{x}sinleft(frac{pi}{2}t^{2}right), dt.

is the Fresnel sine integral. Note that the numerically-computed integral is
within 1.04times10^{-11} of the exact result — well below the
reported error bound.

If the function to integrate takes additional parameters, they can be provided
in the args argument. Suppose that the following integral shall be calculated:

I(a,b)=int_{0}^{1} ax^2+b , dx.

This integral can be evaluated by using the following code:

>>> from scipy.integrate import quad
>>> def integrand(x, a, b):
...     return a*x**2 + b
...
>>> a = 2
>>> b = 1
>>> I = quad(integrand, 0, 1, args=(a,b))
>>> I
(1.6666666666666667, 1.8503717077085944e-14)

Infinite inputs are also allowed in :obj:`quad` by using pm
inf as one of the arguments. For example, suppose that a numerical
value for the exponential integral:

E_{n}left(xright)=int_{1}^{infty}frac{e^{-xt}}{t^{n}}, dt.

is desired (and the fact that this integral can be computed as
special.expn(n,x) is forgotten). The functionality of the function
:obj:`special.expn <scipy.special.expn>` can be replicated by defining a new function
vec_expint based on the routine :obj:`quad`:

>>> from scipy.integrate import quad
>>> import numpy as np
>>> def integrand(t, n, x):
...     return np.exp(-x*t) / t**n
...
>>> def expint(n, x):
...     return quad(integrand, 1, np.inf, args=(n, x))[0]
...
>>> vec_expint = np.vectorize(expint)
>>> vec_expint(3, np.arange(1.0, 4.0, 0.5))
array([ 0.1097,  0.0567,  0.0301,  0.0163,  0.0089,  0.0049])
>>> import scipy.special as special
>>> special.expn(3, np.arange(1.0,4.0,0.5))
array([ 0.1097,  0.0567,  0.0301,  0.0163,  0.0089,  0.0049])

The function which is integrated can even use the quad argument (though the
error bound may underestimate the error due to possible numerical error in the
integrand from the use of :obj:`quad` ). The integral in this case is

I_{n}=int_{0}^{infty}int_{1}^{infty}frac{e^{-xt}}{t^{n}}, dt, dx=frac{1}{n}.
>>> result = quad(lambda x: expint(3, x), 0, np.inf)
>>> print(result)
(0.33333333324560266, 2.8548934485373678e-09)
>>> I3 = 1.0/3.0
>>> print(I3)
0.333333333333
>>> print(I3 - result[0])
8.77306560731e-11

This last example shows that multiple integration can be handled using
repeated calls to :func:`quad`.

Warning

Numerical integration algorithms sample the integrand at a finite number of points.
Consequently, they cannot guarantee accurate results (or accuracy estimates) for
arbitrary integrands and limits of integration. Consider the Gaussian integral,
for example:

>>> def gaussian(x):
...     return np.exp(-x**2)
>>> res = integrate.quad(gaussian, -np.inf, np.inf)
>>> res
(1.7724538509055159, 1.4202636756659625e-08)
>>> np.allclose(res[0], np.sqrt(np.pi))  # compare against theoretical result
True

Since the integrand is nearly zero except near the origin, we would expect
large but finite limits of integration to yield the same result. However:

>>> integrate.quad(gaussian, -10000, 10000)
(1.975190562208035e-203, 0.0)

This happens because the adaptive quadrature routine implemented in :func:`quad`,
while working as designed, does not notice the small, important part of the function
within such a large, finite interval. For best results, consider using integration
limits that tightly surround the important part of the integrand.

>>> integrate.quad(gaussian, -15, 15)
(1.772453850905516, 8.476526631214648e-11)

Integrands with several important regions can be broken into pieces as necessary.

General multiple integration (:func:`dblquad`, :func:`tplquad`, :func:`nquad`)

The mechanics for double and triple integration have been wrapped up into the
functions :obj:`dblquad` and :obj:`tplquad`. These functions take the function
to integrate and four, or six arguments, respectively. The limits of all
inner integrals need to be defined as functions.

An example of using double integration to compute several values of
I_{n} is shown below:

>>> from scipy.integrate import quad, dblquad
>>> def I(n):
...     return dblquad(lambda t, x: np.exp(-x*t)/t**n, 0, np.inf, lambda x: 1, lambda x: np.inf)
...
>>> print(I(4))
(0.2500000000043577, 1.29830334693681e-08)
>>> print(I(3))
(0.33333333325010883, 1.3888461883425516e-08)
>>> print(I(2))
(0.4999999999985751, 1.3894083651858995e-08)

As example for non-constant limits consider the integral

I=int_{y=0}^{1/2}int_{x=0}^{1-2y} x y , dx, dy=frac{1}{96}.

This integral can be evaluated using the expression below (Note the use of the
non-constant lambda functions for the upper limit of the inner integral):

>>> from scipy.integrate import dblquad
>>> area = dblquad(lambda x, y: x*y, 0, 0.5, lambda x: 0, lambda x: 1-2*x)
>>> area
(0.010416666666666668, 1.1564823173178715e-16)

For n-fold integration, scipy provides the function :obj:`nquad`. The
integration bounds are an iterable object: either a list of constant bounds,
or a list of functions for the non-constant integration bounds. The order of
integration (and therefore the bounds) is from the innermost integral to the
outermost one.

The integral from above

I_{n}=int_{0}^{infty}int_{1}^{infty}frac{e^{-xt}}{t^{n}}, dt, dx=frac{1}{n}

can be calculated as

>>> from scipy import integrate
>>> N = 5
>>> def f(t, x):
...    return np.exp(-x*t) / t**N
...
>>> integrate.nquad(f, [[1, np.inf],[0, np.inf]])
(0.20000000000002294, 1.2239614263187945e-08)

Note that the order of arguments for f must match the order of the
integration bounds; i.e., the inner integral with respect to t is on
the interval [1, infty] and the outer integral with respect to
x is on the interval [0, infty].

Non-constant integration bounds can be treated in a similar manner; the
example from above

I=int_{y=0}^{1/2}int_{x=0}^{1-2y} x y , dx, dy=frac{1}{96}.

can be evaluated by means of

>>> from scipy import integrate
>>> def f(x, y):
...     return x*y
...
>>> def bounds_y():
...     return [0, 0.5]
...
>>> def bounds_x(y):
...     return [0, 1-2*y]
...
>>> integrate.nquad(f, [bounds_x, bounds_y])
(0.010416666666666668, 4.101620128472366e-16)

which is the same result as before.

Gaussian quadrature

A few functions are also provided in order to perform simple Gaussian
quadrature over a fixed interval. The first is :obj:`fixed_quad`, which
performs fixed-order Gaussian quadrature. The second function is
:obj:`quadrature`, which performs Gaussian quadrature of multiple
orders until the difference in the integral estimate is beneath some
tolerance supplied by the user. These functions both use the module
scipy.special.orthogonal, which can calculate the roots and quadrature
weights of a large variety of orthogonal polynomials (the polynomials
themselves are available as special functions returning instances of
the polynomial class — e.g., :obj:`special.legendre <scipy.special.legendre>`).

Romberg Integration

Romberg’s method [WPR] is another method for numerically evaluating an
integral. See the help function for :func:`romberg` for further details.

Integrating using Samples

If the samples are equally-spaced and the number of samples available
is 2^{k}+1 for some integer k, then Romberg :obj:`romb`
integration can be used to obtain high-precision estimates of the
integral using the available samples. Romberg integration uses the
trapezoid rule at step-sizes related by a power of two and then
performs Richardson extrapolation on these estimates to approximate
the integral with a higher degree of accuracy.

In case of arbitrary spaced samples, the two functions :obj:`trapezoid`
and :obj:`simpson` are available. They are using Newton-Coates formulas
of order 1 and 2 respectively to perform integration. The trapezoidal rule
approximates the function as a straight line between adjacent points, while
Simpson’s rule approximates the function between three adjacent points as a
parabola.

For an odd number of samples that are equally spaced Simpson’s rule is exact
if the function is a polynomial of order 3 or less. If the samples are not
equally spaced, then the result is exact only if the function is a polynomial
of order 2 or less.

>>> import numpy as np
>>> def f1(x):
...    return x**2
...
>>> def f2(x):
...    return x**3
...
>>> x = np.array([1,3,4])
>>> y1 = f1(x)
>>> from scipy import integrate
>>> I1 = integrate.simpson(y1, x)
>>> print(I1)
21.0

This corresponds exactly to

int_{1}^{4} x^2 , dx = 21,

whereas integrating the second function

>>> y2 = f2(x)
>>> I2 = integrate.simpson(y2, x)
>>> print(I2)
61.5

does not correspond to

int_{1}^{4} x^3 , dx = 63.75

because the order of the polynomial in f2 is larger than two.

Faster integration using low-level callback functions

A user desiring reduced integration times may pass a C function
pointer through scipy.LowLevelCallable to quad, dblquad,
tplquad or nquad and it will be integrated and return a result in
Python. The performance increase here arises from two factors. The
primary improvement is faster function evaluation, which is provided
by compilation of the function itself. Additionally we have a speedup
provided by the removal of function calls between C and Python in
:obj:`quad`. This method may provide a speed improvements of ~2x for
trivial functions such as sine but can produce a much more noticeable
improvements (10x+) for more complex functions. This feature then, is
geared towards a user with numerically intensive integrations willing
to write a little C to reduce computation time significantly.

The approach can be used, for example, via ctypes in a few simple steps:

1.) Write an integrand function in C with the function signature
double f(int n, double *x, void *user_data), where x is an
array containing the point the function f is evaluated at, and user_data
to arbitrary additional data you want to provide.

/* testlib.c */
double f(int n, double *x, void *user_data) {
    double c = *(double *)user_data;
    return c + x[0] - x[1] * x[2]; /* corresponds to c + x - y * z */
}

2.) Now compile this file to a shared/dynamic library (a quick search will help
with this as it is OS-dependent). The user must link any math libraries,
etc., used. On linux this looks like:

$ gcc -shared -fPIC -o testlib.so testlib.c

The output library will be referred to as testlib.so, but it may have a
different file extension. A library has now been created that can be loaded
into Python with ctypes.

3.) Load shared library into Python using ctypes and set restypes and
argtypes — this allows SciPy to interpret the function correctly:

import os, ctypes
from scipy import integrate, LowLevelCallable

lib = ctypes.CDLL(os.path.abspath('testlib.so'))
lib.f.restype = ctypes.c_double
lib.f.argtypes = (ctypes.c_int, ctypes.POINTER(ctypes.c_double), ctypes.c_void_p)

c = ctypes.c_double(1.0)
user_data = ctypes.cast(ctypes.pointer(c), ctypes.c_void_p)

func = LowLevelCallable(lib.f, user_data)

The last void *user_data in the function is optional and can be omitted
(both in the C function and ctypes argtypes) if not needed. Note that the
coordinates are passed in as an array of doubles rather than a separate argument.

4.) Now integrate the library function as normally, here using nquad:

>>> integrate.nquad(func, [[0, 10], [-10, 0], [-1, 1]])
(1200.0, 1.1102230246251565e-11)

The Python tuple is returned as expected in a reduced amount of time. All
optional parameters can be used with this method including specifying
singularities, infinite bounds, etc.

Ordinary differential equations (:func:`solve_ivp`)

Integrating a set of ordinary differential equations (ODEs) given
initial conditions is another useful example. The function
:obj:`solve_ivp` is available in SciPy for integrating a first-order
vector differential equation:

frac{dmathbf{y}}{dt}=mathbf{f}left(mathbf{y},tright),

given initial conditions mathbf{y}left(0right)=y_{0}, where
mathbf{y} is a length N vector and mathbf{f}
is a mapping from mathcal{R}^{N} to mathcal{R}^{N}.
A higher-order ordinary differential equation can always be reduced to
a differential equation of this type by introducing intermediate
derivatives into the mathbf{y} vector.

For example, suppose it is desired to find the solution to the
following second-order differential equation:

frac{d^{2}w}{dz^{2}}-zw(z)=0

with initial conditions wleft(0right)=frac{1}{sqrt[3]{3^{2}}Gammaleft(frac{2}{3}right)} and left.frac{dw}{dz}right|_{z=0}=-frac{1}{sqrt[3]{3}Gammaleft(frac{1}{3}right)}. It is known that the solution to this differential equation with these
boundary conditions is the Airy function

w=textrm{Ai}left(zright),

which gives a means to check the integrator using :func:`special.airy <scipy.special.airy>`.

First, convert this ODE into standard form by setting
mathbf{y}=left[frac{dw}{dz},wright] and t=z. Thus,
the differential equation becomes

frac{dmathbf{y}}{dt}=left[begin{array}{c} ty_{1}\ y_{0}end{array}right]=left[begin{array}{cc} 0 & t\ 1 & 0end{array}right]left[begin{array}{c} y_{0}\ y_{1}end{array}right]=left[begin{array}{cc} 0 & t\ 1 & 0end{array}right]mathbf{y}.

In other words,

mathbf{f}left(mathbf{y},tright)=mathbf{A}left(tright)mathbf{y}.

As an interesting reminder, if mathbf{A}left(tright)
commutes with int_{0}^{t}mathbf{A}left(tauright), dtau
under matrix multiplication, then this linear differential equation
has an exact solution using the matrix exponential:

mathbf{y}left(tright)=expleft(int_{0}^{t}mathbf{A}left(tauright)dtauright)mathbf{y}left(0right),

However, in this case, mathbf{A}left(tright) and its integral do not commute.

This differential equation can be solved using the function :obj:`solve_ivp`.
It requires the derivative, fprime, the time span [t_start, t_end]
and the initial conditions vector, y0, as input arguments and returns
an object whose y field is an array with consecutive solution values as
columns. The initial conditions are therefore given in the first output column.

>>> from scipy.integrate import solve_ivp
>>> from scipy.special import gamma, airy
>>> y1_0 = +1 / 3**(2/3) / gamma(2/3)
>>> y0_0 = -1 / 3**(1/3) / gamma(1/3)
>>> y0 = [y0_0, y1_0]
>>> def func(t, y):
...     return [t*y[1],y[0]]
...
>>> t_span = [0, 4]
>>> sol1 = solve_ivp(func, t_span, y0)
>>> print("sol1.t: {}".format(sol1.t))
sol1.t:    [0.         0.10097672 1.04643602 1.91060117 2.49872472 3.08684827
 3.62692846 4.        ]

As it can be seen solve_ivp determines its time steps automatically if not
specified otherwise. To compare the solution of solve_ivp with the airy
function the time vector created by solve_ivp is passed to the airy function.

>>> print("sol1.y[1]: {}".format(sol1.y[1]))
sol1.y[1]: [0.35502805 0.328952   0.12801343 0.04008508 0.01601291 0.00623879
 0.00356316 0.00405982]
>>> print("airy(sol.t)[0]:  {}".format(airy(sol1.t)[0]))
airy(sol.t)[0]: [0.35502805 0.328952   0.12804768 0.03995804 0.01575943 0.00562799
 0.00201689 0.00095156]

The solution of solve_ivp with its standard parameters shows a big deviation
to the airy function. To minimize this deviation, relative and absolute
tolerances can be used.

>>> rtol, atol = (1e-8, 1e-8)
>>> sol2 = solve_ivp(func, t_span, y0, rtol=rtol, atol=atol)
>>> print("sol2.y[1][::6]: {}".format(sol2.y[1][0::6]))
sol2.y[1][::6]: [0.35502805 0.19145234 0.06368989 0.0205917  0.00554734 0.00106409]
>>> print("airy(sol2.t)[0][::6]: {}".format(airy(sol2.t)[0][::6]))
airy(sol2.t)[0][::6]: [0.35502805 0.19145234 0.06368989 0.0205917  0.00554733 0.00106406]

To specify user defined time points for the solution of solve_ivp, solve_ivp
offers two possibilities that can also be used complementarily. By passing the t_eval
option to the function call solve_ivp returns the solutions of these time points
of t_eval in its output.

>>> import numpy as np
>>> t = np.linspace(0, 4, 100)
>>> sol3 = solve_ivp(func, t_span, y0, t_eval=t)

If the jacobian matrix of function is known, it can be passed to the solve_ivp
to achieve better results. Please be aware however that the default integration method
RK45 does not support jacobian matrices and thereby another integration method has
to be chosen. One of the integration methods that support a jacobian matrix is the for
example the Radau method of following example.

>>> def gradient(t, y):
...     return [[0,t], [1,0]]
>>> sol4 = solve_ivp(func, t_span, y0, method='Radau', jac=gradient)

Solving a system with a banded Jacobian matrix

odeint can be told that the Jacobian is banded. For a large
system of differential equations that are known to be stiff, this
can improve performance significantly.

As an example, we’ll solve the 1-D Gray-Scott partial
differential equations using the method of lines [MOL]. The Gray-Scott equations
for the functions u(x, t) and v(x, t) on the interval
x in [0, L] are

begin{split}
frac{partial u}{partial t} = D_u frac{partial^2 u}{partial x^2} - uv^2 + f(1-u) \
frac{partial v}{partial t} = D_v frac{partial^2 v}{partial x^2} + uv^2 - (f + k)v \
end{split}

where D_u and D_v are the diffusion coefficients of the
components u and v, respectively, and f and k
are constants. (For more information about the system, see
http://groups.csail.mit.edu/mac/projects/amorphous/GrayScott/)

We’ll assume Neumann (i.e., «no flux») boundary conditions:

frac{partial u}{partial x}(0,t) = 0, quad
frac{partial v}{partial x}(0,t) = 0, quad
frac{partial u}{partial x}(L,t) = 0, quad
frac{partial v}{partial x}(L,t) = 0

To apply the method of lines, we discretize the x variable by defining
the uniformly spaced grid of N points left{x_0, x_1, ldots, x_{N-1}right}, with
x_0 = 0 and x_{N-1} = L.
We define u_j(t) equiv u(x_k, t) and v_j(t) equiv v(x_k, t), and
replace the x derivatives with finite differences. That is,

frac{partial^2 u}{partial x^2}(x_j, t) rightarrow
    frac{u_{j-1}(t) - 2 u_{j}(t) + u_{j+1}(t)}{(Delta x)^2}

We then have a system of 2N ordinary differential equations:

For convenience, the (t) arguments have been dropped.

To enforce the boundary conditions, we introduce «ghost» points
x_{-1} and x_N, and define u_{-1}(t) equiv u_1(t),
u_N(t) equiv u_{N-2}(t); v_{-1}(t) and v_N(t)
are defined analogously.

Then

and

Our complete system of 2N ordinary differential equations is :eq:`interior`
for k = 1, 2, ldots, N-2, along with :eq:`boundary0` and :eq:`boundaryL`.

We can now starting implementing this system in code. We must combine
{u_k} and {v_k} into a single vector of length 2N.
The two obvious choices are
{u_0, u_1, ldots, u_{N-1}, v_0, v_1, ldots, v_{N-1}}
and
{u_0, v_0, u_1, v_1, ldots, u_{N-1}, v_{N-1}}.
Mathematically, it does not matter, but the choice affects how
efficiently odeint can solve the system. The reason is in how
the order affects the pattern of the nonzero elements of the Jacobian matrix.

When the variables are ordered
as {u_0, u_1, ldots, u_{N-1}, v_0, v_1, ldots, v_{N-1}},
the pattern of nonzero elements of the Jacobian matrix is

begin{smallmatrix}
   * & * & 0 & 0 & 0 & 0 & 0  &  * & 0 & 0 & 0 & 0 & 0 & 0 \
   * & * & * & 0 & 0 & 0 & 0  &  0 & * & 0 & 0 & 0 & 0 & 0 \
   0 & * & * & * & 0 & 0 & 0  &  0 & 0 & * & 0 & 0 & 0 & 0 \
   0 & 0 & * & * & * & 0 & 0  &  0 & 0 & 0 & * & 0 & 0 & 0 \
   0 & 0 & 0 & * & * & * & 0  &  0 & 0 & 0 & 0 & * & 0 & 0 \
   0 & 0 & 0 & 0 & * & * & *  &  0 & 0 & 0 & 0 & 0 & * & 0 \
   0 & 0 & 0 & 0 & 0 & * & *  &  0 & 0 & 0 & 0 & 0 & 0 & * \
   * & 0 & 0 & 0 & 0 & 0 & 0  &  * & * & 0 & 0 & 0 & 0 & 0 \
   0 & * & 0 & 0 & 0 & 0 & 0  &  * & * & * & 0 & 0 & 0 & 0 \
   0 & 0 & * & 0 & 0 & 0 & 0  &  0 & * & * & * & 0 & 0 & 0 \
   0 & 0 & 0 & * & 0 & 0 & 0  &  0 & 0 & * & * & * & 0 & 0 \
   0 & 0 & 0 & 0 & * & 0 & 0  &  0 & 0 & 0 & * & * & * & 0 \
   0 & 0 & 0 & 0 & 0 & * & 0  &  0 & 0 & 0 & 0 & * & * & * \
   0 & 0 & 0 & 0 & 0 & 0 & *  &  0 & 0 & 0 & 0 & ) & * & * \
end{smallmatrix}

The Jacobian pattern with variables interleaved
as {u_0, v_0, u_1, v_1, ldots, u_{N-1}, v_{N-1}} is

begin{smallmatrix}
   * & * & * & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 \
   * & * & 0 & * & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 \
   * & 0 & * & * & * & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 \
   0 & * & * & * & 0 & * & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 \
   0 & 0 & * & 0 & * & * & * & 0 & 0 & 0 & 0 & 0 & 0 & 0 \
   0 & 0 & 0 & * & * & * & 0 & * & 0 & 0 & 0 & 0 & 0 & 0 \
   0 & 0 & 0 & 0 & * & 0 & * & * & * & 0 & 0 & 0 & 0 & 0 \
   0 & 0 & 0 & 0 & 0 & * & * & * & 0 & * & 0 & 0 & 0 & 0 \
   0 & 0 & 0 & 0 & 0 & 0 & * & 0 & * & * & * & 0 & 0 & 0 \
   0 & 0 & 0 & 0 & 0 & 0 & 0 & * & * & * & 0 & * & 0 & 0 \
   0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & * & 0 & * & * & * & 0 \
   0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & * & * & * & 0 & * \
   0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & * & 0 & * & * \
   0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & * & * & * \
end{smallmatrix}

In both cases, there are just five nontrivial diagonals, but
when the variables are interleaved, the bandwidth is much
smaller.
That is, the main diagonal and the two diagonals immediately
above and the two immediately below the main diagonal
are the nonzero diagonals.
This is important, because the inputs mu and ml
of odeint are the upper and lower bandwidths of the
Jacobian matrix. When the variables are interleaved,
mu and ml are 2. When the variables are stacked
with {v_k} following {u_k}, the upper
and lower bandwidths are N.

With that decision made, we can write the function that
implements the system of differential equations.

First, we define the functions for the source and reaction
terms of the system:

def G(u, v, f, k):
    return f * (1 - u) - u*v**2

def H(u, v, f, k):
    return -(f + k) * v + u*v**2

Next, we define the function that computes the right-hand side
of the system of differential equations:

def grayscott1d(y, t, f, k, Du, Dv, dx):
    """
    Differential equations for the 1-D Gray-Scott equations.

    The ODEs are derived using the method of lines.
    """
    # The vectors u and v are interleaved in y.  We define
    # views of u and v by slicing y.
    u = y[::2]
    v = y[1::2]

    # dydt is the return value of this function.
    dydt = np.empty_like(y)

    # Just like u and v are views of the interleaved vectors
    # in y, dudt and dvdt are views of the interleaved output
    # vectors in dydt.
    dudt = dydt[::2]
    dvdt = dydt[1::2]

    # Compute du/dt and dv/dt.  The end points and the interior points
    # are handled separately.
    dudt[0]    = G(u[0],    v[0],    f, k) + Du * (-2.0*u[0] + 2.0*u[1]) / dx**2
    dudt[1:-1] = G(u[1:-1], v[1:-1], f, k) + Du * np.diff(u,2) / dx**2
    dudt[-1]   = G(u[-1],   v[-1],   f, k) + Du * (- 2.0*u[-1] + 2.0*u[-2]) / dx**2
    dvdt[0]    = H(u[0],    v[0],    f, k) + Dv * (-2.0*v[0] + 2.0*v[1]) / dx**2
    dvdt[1:-1] = H(u[1:-1], v[1:-1], f, k) + Dv * np.diff(v,2) / dx**2
    dvdt[-1]   = H(u[-1],   v[-1],   f, k) + Dv * (-2.0*v[-1] + 2.0*v[-2]) / dx**2

    return dydt

We won’t implement a function to compute the Jacobian, but we will tell
odeint that the Jacobian matrix is banded. This allows the underlying
solver (LSODA) to avoid computing values that it knows are zero. For a large
system, this improves the performance significantly, as demonstrated in the
following ipython session.

First, we define the required inputs:

In [30]: rng = np.random.default_rng()

In [31]: y0 = rng.standard_normal(5000)

In [32]: t = np.linspace(0, 50, 11)

In [33]: f = 0.024

In [34]: k = 0.055

In [35]: Du = 0.01

In [36]: Dv = 0.005

In [37]: dx = 0.025

Time the computation without taking advantage of the banded structure
of the Jacobian matrix:

In [38]: %timeit sola = odeint(grayscott1d, y0, t, args=(f, k, Du, Dv, dx))
1 loop, best of 3: 25.2 s per loop

Now set ml=2 and mu=2, so odeint knows that the Jacobian matrix
is banded:

In [39]: %timeit solb = odeint(grayscott1d, y0, t, args=(f, k, Du, Dv, dx), ml=2, mu=2)
10 loops, best of 3: 191 ms per loop

That is quite a bit faster!

Let’s ensure that they have computed the same result:

In [41]: np.allclose(sola, solb)
Out[41]: True

References

In this Python tutorial, we will learn about the “Scipy Integrate” where we will learn about how to use the integration method to solve integration problems. And additionally, we will cover the following topics.

  • Scipy Integrate
  • Scipy Integrate Simpson
  • Scipy Integrate Trapzoid
  • Scipy Integrate Quad
  • Scipy Integrate Odeint
  • Scipy Integrate Solve_Ivp
  • Scipy Integrate CumTrapz

The Scipy submodule scipy.integrate contains the many methods to solve problems related to integrations or differential equations in Python. It has a predefined function and method to solve the integration or differential equation mathematics problems.

To know the available integration techniques within this submodule, use the below code.

from scipy import integrate
print(help(integrate))
Scipy integrate
Scipy integrate

In the above output, when we will scroll through, then it shows all the integration or differential techniques, methods, and functions in this module.

Read: Scipy Stats – Complete Guide

Scipy Integrate Trapzoid

The TrapeZoid rule is an integration technique that evaluates the area under the curve by dividing the total area into a smaller trapezoid. It integrates a given function y(x) based on a specified axis.

The syntax for using it in Python is given below.

scipy.integrate.trapezoid(y, x=None, dx=1.0, axis=- 1)

Where parameters are:

  • y(array_data): It represents the array that we want to integrate as input.
  • x(array_data): It is used to specify the sample points that relate to y values.
  • dx(scalar): It is used to specify the space between sample points when the x isn’t used.
  • axis(int): It defines the on which axis we want to perform the integration.

The method trapezoid() returns the value trapz of type float which is approximated integral value.

Let’s take an example by following the below steps in Python:

Import the required libraries.

from scipy.integrate import trapezoid

Create array values that represent the y data and pass it to the method.

trapezoid([5,8,10])
Scipy Integrate Trapzoid
Scipy Integrate Trapzoid

The output shows the integration value 15.5 by applying the trapezoid rule.

Read: Scipy Misc + Examples

Scipy Integrate Simpson

The Scipy has a method simpson() that calculates the approximate value of an integral. This method exists in the submodule scipy.integrate.

The syntax for using it in Python is given below.

scipy.integrate.simpson(y, x=None, dx=1.0, axis=- 1, even='avg')

Where parameters are:

  • y(array_data): It represents the array that we want to integrate as input.
  • x(array_data): It is used to specify the sample points that relate to y values.
  • dx(scalar): It is used to specify the space between sample points when the x isn’t used.
  • axis(int): It defines the on which axis we want to perform the integration.
  • even(string): It is used to specify the trapezoidal rule on the average of two results, the first and the last interval.

Let’s take an example using the below steps:

Import the required module as shown below code.

import numpy as np
from scipy.integrate import simpson

Create an array of data and sample points using the below code.

array_data = np.arange(5,15)
sample_pnt = np.arange(5,15)

Use the below Python code to calculate the integration using the method simpson().

simpson(array_data,sample_pnt)
Scipy Integrate Simpson
Scipy Integrate Simpson

The output shows the integral value of the array and the given sample points are 85.5.

Read: Scipy Rotate Image + Examples

Scipy Integrate Quad

The Scipy has a method quad() in the submodule scipy.integrate that calculate the definite integral of a given function from infinite interval a to b in Python.

The syntax is given below.

scipy.integrate.quad(func, a, b, args=(), full_output=0)

Where parameters are:

  • func(function): It is used to specify the function that is used for the computation of integration. The function can be one of the following forms.
  1. double func(double y)
  2. double func(double y, void *user_data)
  3. double func(int m, double *yy)
  4. double func(int m, double *yy, void *user_data)
  • a(float): Used to specify the lower limit of integration.
  • b(float): Used to specify the upper limit of integration.
  • args(tuple): If we want to pass extra arguments to a function, then use this parameter.
  • full_output(int): Non-zero value is used to get the dictionary of integration information.

The method returns three important results y the integral value, abserr the estimate of the absolute error, and infodict the dictionary containing additional information.

Let’s take an example by following the below steps:

Import the required library using the below Python code.

from scipy.integrate import quad

Create a function using the lambda function and define the interval as shown in the below code.

n3 = lambda n: n**3
a = 0
b = 5

Now calculate the integration of the function using the below code.

quad(n3, a, b)
Scipy Integrate Quad
Scipy Integrate Quad

The output shows the definite integral value of the function n3 (n to the power 3) is 156.25000.

Read: Scipy Sparse – Helpful Tutorial

Scipy Integrate Odeint

The Scipy submodule scipy.integrate contains method odeint() that integrate ordinary differential equations.

The syntax for using it in Python is given below.

scipy.integrate.odeint(func, y0, t, args=(), Dfun=None, col_deriv=0, full_output=0, printmessg=0)

Where parameters are:

  • func: It computes the derivative of function y at t.
  • y0(array): It is used to provide the initial condition for y.
  • t(array): It is a series of time point
  • args: It is used to provide the extra arguments to a function y.
  • Dfun: Used for the gradient of a function.
  • col_deriv(boolean): For true values Dfun define the derivate down to columns, otherwise across to rows in case of false.
  • printmessg(boolean): Used for printing the convergence message.

The function contains many parameters but here above we have explained only common parameters.

The method odient()returns two values y that are array containing the value of y for each time t and the infodict for additional output information.

Let’s take an example by following the below steps:

Import the required libraries.

from scipy.integrate import odeint
import matplotlib.pyplot as plt
import numpy as np

Define the equation using the below code.

def diff_model(y,t):
    k = 0.5
    dydt = -k * y
    return dydt

Create an initial condition using the below code.

y0 = 3

Create a series of time points using the below code.

t = np.linspace(0,15)

Solve the created equation by providing the parameters using the below code.

y = odeint(diff_model,y0,t)

Now plot the solution using the below code.

plt.plot(t,y)
plt.xlabel('time')
plt.ylabel('y(t)')
plt.show()
Scipy Integrate Odeint
Scipy Integrate Odeint

This is how to integrate ordinary differential equations.

Read: Scipy Constants

Scipy Integrate Solve_Ivp

The Scipy has a method solve_ivp() that integrates a system of ordinary differential equations based on the provided initial value.

The syntax for using it in Python is given below.

scipy.integrate.solve_ivp(fun, t_span, y0, method='BDF', t_eval=None, dense_output=False, events=None, vectorized=True, args=None)

Where parameters are:

  • fun(callable): It is on the right-hand side of the system. The signature of the calling function is fun(x,z) where x represents scalar and z is a ndarray that represent the shape in two way.
  • t_span(two tuple floats): It represents the interval of integration from t0 to t1.
  • y0(array_data like shape(n)): Used for specifying the initial state.
  • method(string or odsolver): It is used to specify which integration method to use like RK45, Radau, RK23, DOP853, BDF, and LSODA.
  • t_eval(array_data): It is used to specify the times at which to store the calculated solution.
  • dense_output(boolean): It is used to specify whether we want to calculate the continuous solution or not.
  • events(callable): It is used for tracking events.
  • Vectorized(boolean): It is used to specify whether we want to implement the function in a vectorized way or not.
  • args(tuple): To pass extra arguments.

The function returns the bunch object containing many values but it has two important values that are y and t.

Let’s take an example by following the below steps:

Import the required libraries using the below python code.

from scipy.integrate import solve_ivp

Create an exponential decay function using the below code.

def exp_decay(t, y): return -1.0 * y

Now apply the method solve_ivp() on exponential decay function using the below code.

solution = solve_ivp(exp_decay, [5, 15], [4, 6, 10])

Check the t value that is stored within the solution.

solution.t

Check the y value that is stored within the solution.

solution.y
Scipy Integrate Solve_Ivp
Scipy Integrate Solve_Ivp

This is how to integrate a system of ordinary differential equations based on the provided initial value.

Read: Scipy Optimize – Helpful Guide

Scipy Integrate CumTrapz

The cumtrapez the rule is an integration technique that cumulatively integrates the given function y(x) with the help of the trapezoid rule.

The syntax is given below.

scipy.integrate.cumtrapz(y, x=None, dx=1.0, axis=- 1, intial=None)

Where parameters are:

  • y(array_data): It represents the array that we want to integrate as input.
  • x(array_data): It is used to specify the sample points that relate to y values.
  • dx(scalar): It is used to specify the space between sample points when the x isn’t used.
  • axis(int): It defines the on which axis we want to perform the integration.
  • initial(scalar): It is used to provide the initial value to function.

The method trapezoid() returns the value res of type ndarray.

Let’s take an example by following the below steps:

Import the required libraries using the below python code.

from scipy.integrate import cumtrapz
import numpy as np

Create variable sample_pts which are sample points and y3 which is for integration using the below code.

sample_pts = np.arange(5, 30)
y_func = np.power(sample_pts, 3)

Use the method cumtrapz() on function using the below code.

cumtrapz(y_func,sample_pts)
Scipy Integrate CumTrapz
Scipy Integrate CumTrapz

This is how to use the method cumtrapz() to integrate the given function.

Also, take a look at some more SciPy tutorials.

  • Python Scipy Special
  • Scipy Signal – Helpful Tutorial
  • Scipy Ndimage Rotate
  • Python Scipy Stats Kurtosis
  • Python Scipy Chi-Square Test
  • Python Scipy Stats Multivariate_Normal
  • Scipy Normal Distribution

In this tutorial, we have learned about the “Scipy Integrate” and we have also covered the following topics.

  • Scipy Integrate
  • Scipy Integrate Simpson
  • Scipy Integrate Trapzoid
  • Scipy Integrate Quad
  • Scipy Integrate Odeint
  • Scipy Integrate Solve_Ivp
  • Scipy Integrate CumTrapz

Fewlines4Biju Bijay

I am Bijay Kumar, a Microsoft MVP in SharePoint. Apart from SharePoint, I started working on Python, Machine learning, and artificial intelligence for the last 5 years. During this time I got expertise in various Python libraries also like Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… for various clients in the United States, Canada, the United Kingdom, Australia, New Zealand, etc. Check out my profile.

Понравилась статья? Поделить с друзьями:
  • Python если ошибка то действие
  • Python вывод текста ошибки
  • Python вывод кода ошибки
  • Python вывести матрицу ошибок
  • Python вектор ошибок