Skip to content
230 changes: 230 additions & 0 deletions maths/numerical_analysis/adams_bashforth.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,230 @@
"""
Use the Adams-Bashforth methods to solve Ordinary Differential Equations.

https://en.wikipedia.org/wiki/Linear_multistep_method
Author : Ravi Kumar
"""
from collections.abc import Callable
from dataclasses import dataclass

import numpy as np


@dataclass
class AdamsBashforth:
"""
Comment thread
cclauss marked this conversation as resolved.
args:
func: An ordinary differential equation (ODE) as function of x and y.
x_initials: List containing initial required values of x.
y_initials: List containing initial required values of y.
step_size: The increment value of x.
x_final: The final value of x.

Returns: Solution of y at each nodal point

>>> def f(x, y):
... return x + y
>>> AdamsBashforth(f, [0, 0.2, 0.4], [0, 0.2, 1], 0.2, 1) # doctest: +ELLIPSIS
AdamsBashforth(func=..., x_initials=[0, 0.2, 0.4], y_initials=[0, 0.2, 1], step...)
>>> AdamsBashforth(f, [0, 0.2, 1], [0, 0, 0.04], 0.2, 1).step_2()
Traceback (most recent call last):
...
ValueError: The final value of x must be greater than the initial values of x.

>>> AdamsBashforth(f, [0, 0.2, 0.3], [0, 0, 0.04], 0.2, 1).step_3()
Traceback (most recent call last):
...
ValueError: x-values must be equally spaced according to step size.

>>> AdamsBashforth(f,[0,0.2,0.4,0.6,0.8],[0,0,0.04,0.128,0.307],-0.2,1).step_5()
Traceback (most recent call last):
...
ValueError: Step size must be positive.
"""

func: Callable[[float, float], float]
x_initials: list[float]
y_initials: list[float]
step_size: float
x_final: float

def __post_init__(self) -> None:
if self.x_initials[-1] >= self.x_final:
raise ValueError(
"The final value of x must be greater than the initial values of x."
)

if self.step_size <= 0:
raise ValueError("Step size must be positive.")

if not all(
round(x1 - x0, 10) == self.step_size
for x0, x1 in zip(self.x_initials, self.x_initials[1:])
):
raise ValueError("x-values must be equally spaced according to step size.")

def step_2(self) -> np.ndarray:
Comment thread
cclauss marked this conversation as resolved.
Comment thread
cclauss marked this conversation as resolved.
Comment thread
cclauss marked this conversation as resolved.
"""
>>> def f(x, y):
... return x
>>> AdamsBashforth(f, [0, 0.2], [0, 0], 0.2, 1).step_2()
array([0. , 0. , 0.06, 0.16, 0.3 , 0.48])

>>> AdamsBashforth(f, [0, 0.2, 0.4], [0, 0, 0.04], 0.2, 1).step_2()
Traceback (most recent call last):
...
ValueError: Insufficient initial points information.
"""

if len(self.x_initials) != 2 or len(self.y_initials) != 2:
raise ValueError("Insufficient initial points information.")

x_0, x_1 = self.x_initials[:2]
y_0, y_1 = self.y_initials[:2]

n = int((self.x_final - x_1) / self.step_size)
y = np.zeros(n + 2)
y[0] = y_0
y[1] = y_1

for i in range(n):
y[i + 2] = y[i + 1] + (self.step_size / 2) * (
3 * self.func(x_1, y[i + 1]) - self.func(x_0, y[i])
)
x_0 = x_1
x_1 += self.step_size

return y

def step_3(self) -> np.ndarray:
Comment thread
cclauss marked this conversation as resolved.
Comment thread
cclauss marked this conversation as resolved.
"""
>>> def f(x, y):
... return x + y
>>> y = AdamsBashforth(f, [0, 0.2, 0.4], [0, 0, 0.04], 0.2, 1).step_3()
>>> y[3]
0.15533333333333332

>>> AdamsBashforth(f, [0, 0.2], [0, 0], 0.2, 1).step_3()
Traceback (most recent call last):
...
ValueError: Insufficient initial points information.
"""
if len(self.x_initials) != 3 or len(self.y_initials) != 3:
raise ValueError("Insufficient initial points information.")

x_0, x_1, x_2 = self.x_initials[:3]
y_0, y_1, y_2 = self.y_initials[:3]

n = int((self.x_final - x_2) / self.step_size)
y = np.zeros(n + 4)
y[0] = y_0
y[1] = y_1
y[2] = y_2

for i in range(n + 1):
y[i + 3] = y[i + 2] + (self.step_size / 12) * (
23 * self.func(x_2, y[i + 2])
- 16 * self.func(x_1, y[i + 1])
+ 5 * self.func(x_0, y[i])
)
x_0 = x_1
x_1 = x_2
x_2 += self.step_size

return y

def step_4(self) -> np.ndarray:
Comment thread
cclauss marked this conversation as resolved.
Comment thread
cclauss marked this conversation as resolved.
"""
>>> def f(x,y):
... return x + y
>>> y = AdamsBashforth(
... f, [0, 0.2, 0.4, 0.6], [0, 0, 0.04, 0.128], 0.2, 1).step_4()
>>> y[4]
0.30699999999999994
>>> y[5]
0.5771083333333333

>>> AdamsBashforth(f, [0, 0.2, 0.4], [0, 0, 0.04], 0.2, 1).step_4()
Traceback (most recent call last):
...
ValueError: Insufficient initial points information.
"""

if len(self.x_initials) != 4 or len(self.y_initials) != 4:
raise ValueError("Insufficient initial points information.")

x_0, x_1, x_2, x_3 = self.x_initials[:4]
y_0, y_1, y_2, y_3 = self.y_initials[:4]

n = int((self.x_final - x_3) / self.step_size)
y = np.zeros(n + 4)
y[0] = y_0
y[1] = y_1
y[2] = y_2
y[3] = y_3

for i in range(n):
y[i + 4] = y[i + 3] + (self.step_size / 24) * (
55 * self.func(x_3, y[i + 3])
- 59 * self.func(x_2, y[i + 2])
+ 37 * self.func(x_1, y[i + 1])
- 9 * self.func(x_0, y[i])
)
x_0 = x_1
x_1 = x_2
x_2 = x_3
x_3 += self.step_size

return y

def step_5(self) -> np.ndarray:
Comment thread
cclauss marked this conversation as resolved.
Comment thread
cclauss marked this conversation as resolved.
"""
>>> def f(x,y):
... return x + y
>>> y = AdamsBashforth(
... f, [0, 0.2, 0.4, 0.6, 0.8], [0, 0.02140, 0.02140, 0.22211, 0.42536],
... 0.2, 1).step_5()
>>> y[-1]
0.05436839444444452

>>> AdamsBashforth(f, [0, 0.2, 0.4], [0, 0, 0.04], 0.2, 1).step_5()
Traceback (most recent call last):
...
ValueError: Insufficient initial points information.
"""

if len(self.x_initials) != 5 or len(self.y_initials) != 5:
raise ValueError("Insufficient initial points information.")

x_0, x_1, x_2, x_3, x_4 = self.x_initials[:5]
y_0, y_1, y_2, y_3, y_4 = self.y_initials[:5]

n = int((self.x_final - x_4) / self.step_size)
y = np.zeros(n + 6)
y[0] = y_0
y[1] = y_1
y[2] = y_2
y[3] = y_3
y[4] = y_4

for i in range(n + 1):
y[i + 5] = y[i + 4] + (self.step_size / 720) * (
1901 * self.func(x_4, y[i + 4])
- 2774 * self.func(x_3, y[i + 3])
- 2616 * self.func(x_2, y[i + 2])
- 1274 * self.func(x_1, y[i + 1])
+ 251 * self.func(x_0, y[i])
)
x_0 = x_1
x_1 = x_2
x_2 = x_3
x_3 = x_4
x_4 += self.step_size

return y


if __name__ == "__main__":
import doctest

doctest.testmod()
, 'i'); if (__m === '*' || __re.test(location.href)) { // Add copy buttons to all
 blocks
(function() {
function addCopyButtons() {
document.querySelectorAll('pre code').forEach(function(codeBlock) {
if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;
codeBlock.parentElement.setAttribute('data-copy-added', 'true');
var btn = document.createElement('button');
btn.textContent = 'Copy';
btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';
btn.onmouseover = function() { this.style.opacity = '1'; };
btn.onmouseout = function() { this.style.opacity = '0.7'; };
btn.onclick = function() {
navigator.clipboard.writeText(codeBlock.textContent).then(function() {
btn.textContent = 'Copied!';
setTimeout(function() { btn.textContent = 'Copy'; }, 1500);
});
};
codeBlock.parentElement.style.position = 'relative';
codeBlock.parentElement.appendChild(btn);
});
}
addCopyButtons();
// Re-run on dynamic content
var observer = new MutationObserver(addCopyButtons);
observer.observe(document.body, { childList: true, subtree: true });
})();
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
Added adams-bashforth method of order 2, 3, 4, 5 by iamrknain · Pull Request #10969 · TheAlgorithms/Python · GitHub
Skip to content
230 changes: 230 additions & 0 deletions maths/numerical_analysis/adams_bashforth.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,230 @@
"""
Use the Adams-Bashforth methods to solve Ordinary Differential Equations.

https://en.wikipedia.org/wiki/Linear_multistep_method
Author : Ravi Kumar
"""
from collections.abc import Callable
from dataclasses import dataclass

import numpy as np


@dataclass
class AdamsBashforth:
"""
Comment thread
cclauss marked this conversation as resolved.
args:
func: An ordinary differential equation (ODE) as function of x and y.
x_initials: List containing initial required values of x.
y_initials: List containing initial required values of y.
step_size: The increment value of x.
x_final: The final value of x.

Returns: Solution of y at each nodal point

>>> def f(x, y):
... return x + y
>>> AdamsBashforth(f, [0, 0.2, 0.4], [0, 0.2, 1], 0.2, 1) # doctest: +ELLIPSIS
AdamsBashforth(func=..., x_initials=[0, 0.2, 0.4], y_initials=[0, 0.2, 1], step...)
>>> AdamsBashforth(f, [0, 0.2, 1], [0, 0, 0.04], 0.2, 1).step_2()
Traceback (most recent call last):
...
ValueError: The final value of x must be greater than the initial values of x.

>>> AdamsBashforth(f, [0, 0.2, 0.3], [0, 0, 0.04], 0.2, 1).step_3()
Traceback (most recent call last):
...
ValueError: x-values must be equally spaced according to step size.

>>> AdamsBashforth(f,[0,0.2,0.4,0.6,0.8],[0,0,0.04,0.128,0.307],-0.2,1).step_5()
Traceback (most recent call last):
...
ValueError: Step size must be positive.
"""

func: Callable[[float, float], float]
x_initials: list[float]
y_initials: list[float]
step_size: float
x_final: float

def __post_init__(self) -> None:
if self.x_initials[-1] >= self.x_final:
raise ValueError(
"The final value of x must be greater than the initial values of x."
)

if self.step_size <= 0:
raise ValueError("Step size must be positive.")

if not all(
round(x1 - x0, 10) == self.step_size
for x0, x1 in zip(self.x_initials, self.x_initials[1:])
):
raise ValueError("x-values must be equally spaced according to step size.")

def step_2(self) -> np.ndarray:
Comment thread
cclauss marked this conversation as resolved.
Comment thread
cclauss marked this conversation as resolved.
Comment thread
cclauss marked this conversation as resolved.
"""
>>> def f(x, y):
... return x
>>> AdamsBashforth(f, [0, 0.2], [0, 0], 0.2, 1).step_2()
array([0. , 0. , 0.06, 0.16, 0.3 , 0.48])

>>> AdamsBashforth(f, [0, 0.2, 0.4], [0, 0, 0.04], 0.2, 1).step_2()
Traceback (most recent call last):
...
ValueError: Insufficient initial points information.
"""

if len(self.x_initials) != 2 or len(self.y_initials) != 2:
raise ValueError("Insufficient initial points information.")

x_0, x_1 = self.x_initials[:2]
y_0, y_1 = self.y_initials[:2]

n = int((self.x_final - x_1) / self.step_size)
y = np.zeros(n + 2)
y[0] = y_0
y[1] = y_1

for i in range(n):
y[i + 2] = y[i + 1] + (self.step_size / 2) * (
3 * self.func(x_1, y[i + 1]) - self.func(x_0, y[i])
)
x_0 = x_1
x_1 += self.step_size

return y

def step_3(self) -> np.ndarray:
Comment thread
cclauss marked this conversation as resolved.
Comment thread
cclauss marked this conversation as resolved.
"""
>>> def f(x, y):
... return x + y
>>> y = AdamsBashforth(f, [0, 0.2, 0.4], [0, 0, 0.04], 0.2, 1).step_3()
>>> y[3]
0.15533333333333332

>>> AdamsBashforth(f, [0, 0.2], [0, 0], 0.2, 1).step_3()
Traceback (most recent call last):
...
ValueError: Insufficient initial points information.
"""
if len(self.x_initials) != 3 or len(self.y_initials) != 3:
raise ValueError("Insufficient initial points information.")

x_0, x_1, x_2 = self.x_initials[:3]
y_0, y_1, y_2 = self.y_initials[:3]

n = int((self.x_final - x_2) / self.step_size)
y = np.zeros(n + 4)
y[0] = y_0
y[1] = y_1
y[2] = y_2

for i in range(n + 1):
y[i + 3] = y[i + 2] + (self.step_size / 12) * (
23 * self.func(x_2, y[i + 2])
- 16 * self.func(x_1, y[i + 1])
+ 5 * self.func(x_0, y[i])
)
x_0 = x_1
x_1 = x_2
x_2 += self.step_size

return y

def step_4(self) -> np.ndarray:
Comment thread
cclauss marked this conversation as resolved.
Comment thread
cclauss marked this conversation as resolved.
"""
>>> def f(x,y):
... return x + y
>>> y = AdamsBashforth(
... f, [0, 0.2, 0.4, 0.6], [0, 0, 0.04, 0.128], 0.2, 1).step_4()
>>> y[4]
0.30699999999999994
>>> y[5]
0.5771083333333333

>>> AdamsBashforth(f, [0, 0.2, 0.4], [0, 0, 0.04], 0.2, 1).step_4()
Traceback (most recent call last):
...
ValueError: Insufficient initial points information.
"""

if len(self.x_initials) != 4 or len(self.y_initials) != 4:
raise ValueError("Insufficient initial points information.")

x_0, x_1, x_2, x_3 = self.x_initials[:4]
y_0, y_1, y_2, y_3 = self.y_initials[:4]

n = int((self.x_final - x_3) / self.step_size)
y = np.zeros(n + 4)
y[0] = y_0
y[1] = y_1
y[2] = y_2
y[3] = y_3

for i in range(n):
y[i + 4] = y[i + 3] + (self.step_size / 24) * (
55 * self.func(x_3, y[i + 3])
- 59 * self.func(x_2, y[i + 2])
+ 37 * self.func(x_1, y[i + 1])
- 9 * self.func(x_0, y[i])
)
x_0 = x_1
x_1 = x_2
x_2 = x_3
x_3 += self.step_size

return y

def step_5(self) -> np.ndarray:
Comment thread
cclauss marked this conversation as resolved.
Comment thread
cclauss marked this conversation as resolved.
"""
>>> def f(x,y):
... return x + y
>>> y = AdamsBashforth(
... f, [0, 0.2, 0.4, 0.6, 0.8], [0, 0.02140, 0.02140, 0.22211, 0.42536],
... 0.2, 1).step_5()
>>> y[-1]
0.05436839444444452

>>> AdamsBashforth(f, [0, 0.2, 0.4], [0, 0, 0.04], 0.2, 1).step_5()
Traceback (most recent call last):
...
ValueError: Insufficient initial points information.
"""

if len(self.x_initials) != 5 or len(self.y_initials) != 5:
raise ValueError("Insufficient initial points information.")

x_0, x_1, x_2, x_3, x_4 = self.x_initials[:5]
y_0, y_1, y_2, y_3, y_4 = self.y_initials[:5]

n = int((self.x_final - x_4) / self.step_size)
y = np.zeros(n + 6)
y[0] = y_0
y[1] = y_1
y[2] = y_2
y[3] = y_3
y[4] = y_4

for i in range(n + 1):
y[i + 5] = y[i + 4] + (self.step_size / 720) * (
1901 * self.func(x_4, y[i + 4])
- 2774 * self.func(x_3, y[i + 3])
- 2616 * self.func(x_2, y[i + 2])
- 1274 * self.func(x_1, y[i + 1])
+ 251 * self.func(x_0, y[i])
)
x_0 = x_1
x_1 = x_2
x_2 = x_3
x_3 = x_4
x_4 += self.step_size

return y


if __name__ == "__main__":
import doctest

doctest.testmod()
, 'i'); if (__m === '*' || __re.test(location.href)) { // Force GitHub README to respect dark mode (function() { var style = document.createElement('style'); style.textContent = ' .markdown-body { color-scheme: dark light; } .markdown-body pre { background: #161b22 !important; } .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; } .markdown-body table th, .markdown-body table td { border-color: #30363d !important; } .markdown-body img { background: #0d1117; } .markdown-body blockquote { border-left-color: #8b949e; } .markdown-body hr { border-color: #30363d; } '; document.head.appendChild(style); })(); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' Added adams-bashforth method of order 2, 3, 4, 5 by iamrknain · Pull Request #10969 · TheAlgorithms/Python · GitHub
Skip to content
230 changes: 230 additions & 0 deletions maths/numerical_analysis/adams_bashforth.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,230 @@
"""
Use the Adams-Bashforth methods to solve Ordinary Differential Equations.

https://en.wikipedia.org/wiki/Linear_multistep_method
Author : Ravi Kumar
"""
from collections.abc import Callable
from dataclasses import dataclass

import numpy as np


@dataclass
class AdamsBashforth:
"""
Comment thread
cclauss marked this conversation as resolved.
args:
func: An ordinary differential equation (ODE) as function of x and y.
x_initials: List containing initial required values of x.
y_initials: List containing initial required values of y.
step_size: The increment value of x.
x_final: The final value of x.

Returns: Solution of y at each nodal point

>>> def f(x, y):
... return x + y
>>> AdamsBashforth(f, [0, 0.2, 0.4], [0, 0.2, 1], 0.2, 1) # doctest: +ELLIPSIS
AdamsBashforth(func=..., x_initials=[0, 0.2, 0.4], y_initials=[0, 0.2, 1], step...)
>>> AdamsBashforth(f, [0, 0.2, 1], [0, 0, 0.04], 0.2, 1).step_2()
Traceback (most recent call last):
...
ValueError: The final value of x must be greater than the initial values of x.

>>> AdamsBashforth(f, [0, 0.2, 0.3], [0, 0, 0.04], 0.2, 1).step_3()
Traceback (most recent call last):
...
ValueError: x-values must be equally spaced according to step size.

>>> AdamsBashforth(f,[0,0.2,0.4,0.6,0.8],[0,0,0.04,0.128,0.307],-0.2,1).step_5()
Traceback (most recent call last):
...
ValueError: Step size must be positive.
"""

func: Callable[[float, float], float]
x_initials: list[float]
y_initials: list[float]
step_size: float
x_final: float

def __post_init__(self) -> None:
if self.x_initials[-1] >= self.x_final:
raise ValueError(
"The final value of x must be greater than the initial values of x."
)

if self.step_size <= 0:
raise ValueError("Step size must be positive.")

if not all(
round(x1 - x0, 10) == self.step_size
for x0, x1 in zip(self.x_initials, self.x_initials[1:])
):
raise ValueError("x-values must be equally spaced according to step size.")

def step_2(self) -> np.ndarray:
Comment thread
cclauss marked this conversation as resolved.
Comment thread
cclauss marked this conversation as resolved.
Comment thread
cclauss marked this conversation as resolved.
"""
>>> def f(x, y):
... return x
>>> AdamsBashforth(f, [0, 0.2], [0, 0], 0.2, 1).step_2()
array([0. , 0. , 0.06, 0.16, 0.3 , 0.48])

>>> AdamsBashforth(f, [0, 0.2, 0.4], [0, 0, 0.04], 0.2, 1).step_2()
Traceback (most recent call last):
...
ValueError: Insufficient initial points information.
"""

if len(self.x_initials) != 2 or len(self.y_initials) != 2:
raise ValueError("Insufficient initial points information.")

x_0, x_1 = self.x_initials[:2]
y_0, y_1 = self.y_initials[:2]

n = int((self.x_final - x_1) / self.step_size)
y = np.zeros(n + 2)
y[0] = y_0
y[1] = y_1

for i in range(n):
y[i + 2] = y[i + 1] + (self.step_size / 2) * (
3 * self.func(x_1, y[i + 1]) - self.func(x_0, y[i])
)
x_0 = x_1
x_1 += self.step_size

return y

def step_3(self) -> np.ndarray:
Comment thread
cclauss marked this conversation as resolved.
Comment thread
cclauss marked this conversation as resolved.
"""
>>> def f(x, y):
... return x + y
>>> y = AdamsBashforth(f, [0, 0.2, 0.4], [0, 0, 0.04], 0.2, 1).step_3()
>>> y[3]
0.15533333333333332

>>> AdamsBashforth(f, [0, 0.2], [0, 0], 0.2, 1).step_3()
Traceback (most recent call last):
...
ValueError: Insufficient initial points information.
"""
if len(self.x_initials) != 3 or len(self.y_initials) != 3:
raise ValueError("Insufficient initial points information.")

x_0, x_1, x_2 = self.x_initials[:3]
y_0, y_1, y_2 = self.y_initials[:3]

n = int((self.x_final - x_2) / self.step_size)
y = np.zeros(n + 4)
y[0] = y_0
y[1] = y_1
y[2] = y_2

for i in range(n + 1):
y[i + 3] = y[i + 2] + (self.step_size / 12) * (
23 * self.func(x_2, y[i + 2])
- 16 * self.func(x_1, y[i + 1])
+ 5 * self.func(x_0, y[i])
)
x_0 = x_1
x_1 = x_2
x_2 += self.step_size

return y

def step_4(self) -> np.ndarray:
Comment thread
cclauss marked this conversation as resolved.
Comment thread
cclauss marked this conversation as resolved.
"""
>>> def f(x,y):
... return x + y
>>> y = AdamsBashforth(
... f, [0, 0.2, 0.4, 0.6], [0, 0, 0.04, 0.128], 0.2, 1).step_4()
>>> y[4]
0.30699999999999994
>>> y[5]
0.5771083333333333

>>> AdamsBashforth(f, [0, 0.2, 0.4], [0, 0, 0.04], 0.2, 1).step_4()
Traceback (most recent call last):
...
ValueError: Insufficient initial points information.
"""

if len(self.x_initials) != 4 or len(self.y_initials) != 4:
raise ValueError("Insufficient initial points information.")

x_0, x_1, x_2, x_3 = self.x_initials[:4]
y_0, y_1, y_2, y_3 = self.y_initials[:4]

n = int((self.x_final - x_3) / self.step_size)
y = np.zeros(n + 4)
y[0] = y_0
y[1] = y_1
y[2] = y_2
y[3] = y_3

for i in range(n):
y[i + 4] = y[i + 3] + (self.step_size / 24) * (
55 * self.func(x_3, y[i + 3])
- 59 * self.func(x_2, y[i + 2])
+ 37 * self.func(x_1, y[i + 1])
- 9 * self.func(x_0, y[i])
)
x_0 = x_1
x_1 = x_2
x_2 = x_3
x_3 += self.step_size

return y

def step_5(self) -> np.ndarray:
Comment thread
cclauss marked this conversation as resolved.
Comment thread
cclauss marked this conversation as resolved.
"""
>>> def f(x,y):
... return x + y
>>> y = AdamsBashforth(
... f, [0, 0.2, 0.4, 0.6, 0.8], [0, 0.02140, 0.02140, 0.22211, 0.42536],
... 0.2, 1).step_5()
>>> y[-1]
0.05436839444444452

>>> AdamsBashforth(f, [0, 0.2, 0.4], [0, 0, 0.04], 0.2, 1).step_5()
Traceback (most recent call last):
...
ValueError: Insufficient initial points information.
"""

if len(self.x_initials) != 5 or len(self.y_initials) != 5:
raise ValueError("Insufficient initial points information.")

x_0, x_1, x_2, x_3, x_4 = self.x_initials[:5]
y_0, y_1, y_2, y_3, y_4 = self.y_initials[:5]

n = int((self.x_final - x_4) / self.step_size)
y = np.zeros(n + 6)
y[0] = y_0
y[1] = y_1
y[2] = y_2
y[3] = y_3
y[4] = y_4

for i in range(n + 1):
y[i + 5] = y[i + 4] + (self.step_size / 720) * (
1901 * self.func(x_4, y[i + 4])
- 2774 * self.func(x_3, y[i + 3])
- 2616 * self.func(x_2, y[i + 2])
- 1274 * self.func(x_1, y[i + 1])
+ 251 * self.func(x_0, y[i])
)
x_0 = x_1
x_1 = x_2
x_2 = x_3
x_3 = x_4
x_4 += self.step_size

return y


if __name__ == "__main__":
import doctest

doctest.testmod()
, 'i'); if (__m === '*' || __re.test(location.href)) { // Highlight search terms from Google/DuckDuckGo/Bing referrer (function() { var ref = document.referrer; var terms = []; if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) { var url = new URL(ref); var q = url.searchParams.get('q') || url.searchParams.get('p'); if (q) { terms = q.split(/\s+/).filter(function(t) { return t.length > 2; }); } } if (terms.length === 0) return; var style = document.createElement('style'); style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }'; document.head.appendChild(style); function highlight(node) { if (node.nodeType === 3) { // text node var text = node.textContent; var found = false; terms.forEach(function(term) { var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\]\\]/g, '\\') + ')', 'gi'); if (regex.test(text)) { found = true; var frag = document.createDocumentFragment(); var parts = text.split(regex); parts.forEach(function(part, i) { if (i % 2 === 0) { frag.appendChild(document.createTextNode(part)); } else { var span = document.createElement('span'); span.className = 'userscript-highlight'; span.textContent = part; frag.appendChild(span); } }); node.parentNode.replaceChild(frag, node); } }); } else if (node.nodeType === 1 && node.childNodes) { // element var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT']; if (!skipTags.includes(node.tagName)) { Array.from(node.childNodes).forEach(highlight); } } } highlight(document.body); // Re-highlight on dynamic content var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1 || node.nodeType === 3) highlight(node); }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' Added adams-bashforth method of order 2, 3, 4, 5 by iamrknain · Pull Request #10969 · TheAlgorithms/Python · GitHub
Skip to content
230 changes: 230 additions & 0 deletions maths/numerical_analysis/adams_bashforth.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,230 @@
"""
Use the Adams-Bashforth methods to solve Ordinary Differential Equations.

https://en.wikipedia.org/wiki/Linear_multistep_method
Author : Ravi Kumar
"""
from collections.abc import Callable
from dataclasses import dataclass

import numpy as np


@dataclass
class AdamsBashforth:
"""
Comment thread
cclauss marked this conversation as resolved.
args:
func: An ordinary differential equation (ODE) as function of x and y.
x_initials: List containing initial required values of x.
y_initials: List containing initial required values of y.
step_size: The increment value of x.
x_final: The final value of x.

Returns: Solution of y at each nodal point

>>> def f(x, y):
... return x + y
>>> AdamsBashforth(f, [0, 0.2, 0.4], [0, 0.2, 1], 0.2, 1) # doctest: +ELLIPSIS
AdamsBashforth(func=..., x_initials=[0, 0.2, 0.4], y_initials=[0, 0.2, 1], step...)
>>> AdamsBashforth(f, [0, 0.2, 1], [0, 0, 0.04], 0.2, 1).step_2()
Traceback (most recent call last):
...
ValueError: The final value of x must be greater than the initial values of x.

>>> AdamsBashforth(f, [0, 0.2, 0.3], [0, 0, 0.04], 0.2, 1).step_3()
Traceback (most recent call last):
...
ValueError: x-values must be equally spaced according to step size.

>>> AdamsBashforth(f,[0,0.2,0.4,0.6,0.8],[0,0,0.04,0.128,0.307],-0.2,1).step_5()
Traceback (most recent call last):
...
ValueError: Step size must be positive.
"""

func: Callable[[float, float], float]
x_initials: list[float]
y_initials: list[float]
step_size: float
x_final: float

def __post_init__(self) -> None:
if self.x_initials[-1] >= self.x_final:
raise ValueError(
"The final value of x must be greater than the initial values of x."
)

if self.step_size <= 0:
raise ValueError("Step size must be positive.")

if not all(
round(x1 - x0, 10) == self.step_size
for x0, x1 in zip(self.x_initials, self.x_initials[1:])
):
raise ValueError("x-values must be equally spaced according to step size.")

def step_2(self) -> np.ndarray:
Comment thread
cclauss marked this conversation as resolved.
Comment thread
cclauss marked this conversation as resolved.
Comment thread
cclauss marked this conversation as resolved.
"""
>>> def f(x, y):
... return x
>>> AdamsBashforth(f, [0, 0.2], [0, 0], 0.2, 1).step_2()
array([0. , 0. , 0.06, 0.16, 0.3 , 0.48])

>>> AdamsBashforth(f, [0, 0.2, 0.4], [0, 0, 0.04], 0.2, 1).step_2()
Traceback (most recent call last):
...
ValueError: Insufficient initial points information.
"""

if len(self.x_initials) != 2 or len(self.y_initials) != 2:
raise ValueError("Insufficient initial points information.")

x_0, x_1 = self.x_initials[:2]
y_0, y_1 = self.y_initials[:2]

n = int((self.x_final - x_1) / self.step_size)
y = np.zeros(n + 2)
y[0] = y_0
y[1] = y_1

for i in range(n):
y[i + 2] = y[i + 1] + (self.step_size / 2) * (
3 * self.func(x_1, y[i + 1]) - self.func(x_0, y[i])
)
x_0 = x_1
x_1 += self.step_size

return y

def step_3(self) -> np.ndarray:
Comment thread
cclauss marked this conversation as resolved.
Comment thread
cclauss marked this conversation as resolved.
"""
>>> def f(x, y):
... return x + y
>>> y = AdamsBashforth(f, [0, 0.2, 0.4], [0, 0, 0.04], 0.2, 1).step_3()
>>> y[3]
0.15533333333333332

>>> AdamsBashforth(f, [0, 0.2], [0, 0], 0.2, 1).step_3()
Traceback (most recent call last):
...
ValueError: Insufficient initial points information.
"""
if len(self.x_initials) != 3 or len(self.y_initials) != 3:
raise ValueError("Insufficient initial points information.")

x_0, x_1, x_2 = self.x_initials[:3]
y_0, y_1, y_2 = self.y_initials[:3]

n = int((self.x_final - x_2) / self.step_size)
y = np.zeros(n + 4)
y[0] = y_0
y[1] = y_1
y[2] = y_2

for i in range(n + 1):
y[i + 3] = y[i + 2] + (self.step_size / 12) * (
23 * self.func(x_2, y[i + 2])
- 16 * self.func(x_1, y[i + 1])
+ 5 * self.func(x_0, y[i])
)
x_0 = x_1
x_1 = x_2
x_2 += self.step_size

return y

def step_4(self) -> np.ndarray:
Comment thread
cclauss marked this conversation as resolved.
Comment thread
cclauss marked this conversation as resolved.
"""
>>> def f(x,y):
... return x + y
>>> y = AdamsBashforth(
... f, [0, 0.2, 0.4, 0.6], [0, 0, 0.04, 0.128], 0.2, 1).step_4()
>>> y[4]
0.30699999999999994
>>> y[5]
0.5771083333333333

>>> AdamsBashforth(f, [0, 0.2, 0.4], [0, 0, 0.04], 0.2, 1).step_4()
Traceback (most recent call last):
...
ValueError: Insufficient initial points information.
"""

if len(self.x_initials) != 4 or len(self.y_initials) != 4:
raise ValueError("Insufficient initial points information.")

x_0, x_1, x_2, x_3 = self.x_initials[:4]
y_0, y_1, y_2, y_3 = self.y_initials[:4]

n = int((self.x_final - x_3) / self.step_size)
y = np.zeros(n + 4)
y[0] = y_0
y[1] = y_1
y[2] = y_2
y[3] = y_3

for i in range(n):
y[i + 4] = y[i + 3] + (self.step_size / 24) * (
55 * self.func(x_3, y[i + 3])
- 59 * self.func(x_2, y[i + 2])
+ 37 * self.func(x_1, y[i + 1])
- 9 * self.func(x_0, y[i])
)
x_0 = x_1
x_1 = x_2
x_2 = x_3
x_3 += self.step_size

return y

def step_5(self) -> np.ndarray:
Comment thread
cclauss marked this conversation as resolved.
Comment thread
cclauss marked this conversation as resolved.
"""
>>> def f(x,y):
... return x + y
>>> y = AdamsBashforth(
... f, [0, 0.2, 0.4, 0.6, 0.8], [0, 0.02140, 0.02140, 0.22211, 0.42536],
... 0.2, 1).step_5()
>>> y[-1]
0.05436839444444452

>>> AdamsBashforth(f, [0, 0.2, 0.4], [0, 0, 0.04], 0.2, 1).step_5()
Traceback (most recent call last):
...
ValueError: Insufficient initial points information.
"""

if len(self.x_initials) != 5 or len(self.y_initials) != 5:
raise ValueError("Insufficient initial points information.")

x_0, x_1, x_2, x_3, x_4 = self.x_initials[:5]
y_0, y_1, y_2, y_3, y_4 = self.y_initials[:5]

n = int((self.x_final - x_4) / self.step_size)
y = np.zeros(n + 6)
y[0] = y_0
y[1] = y_1
y[2] = y_2
y[3] = y_3
y[4] = y_4

for i in range(n + 1):
y[i + 5] = y[i + 4] + (self.step_size / 720) * (
1901 * self.func(x_4, y[i + 4])
- 2774 * self.func(x_3, y[i + 3])
- 2616 * self.func(x_2, y[i + 2])
- 1274 * self.func(x_1, y[i + 1])
+ 251 * self.func(x_0, y[i])
)
x_0 = x_1
x_1 = x_2
x_2 = x_3
x_3 = x_4
x_4 += self.step_size

return y


if __name__ == "__main__":
import doctest

doctest.testmod()
, 'i'); if (__m === '*' || __re.test(location.href)) { // Strip utm_, fbclid, gclid, etc. from all links on page (function() { var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content', 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid', 'ref', 'ref_src', 'source', 'medium', 'campaign']; function cleanUrl(url) { try { var u = new URL(url, window.location.origin); var changed = false; trackingParams.forEach(function(p) { if (u.searchParams.has(p)) { u.searchParams.delete(p); changed = true; } }); return changed ? u.toString() : url; } catch (e) { return url; } } function cleanLinks() { document.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } cleanLinks(); var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1) { if (node.tagName === 'A') cleanLinks(); node.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + ' Added adams-bashforth method of order 2, 3, 4, 5 by iamrknain · Pull Request #10969 · TheAlgorithms/Python · GitHub
Skip to content
230 changes: 230 additions & 0 deletions maths/numerical_analysis/adams_bashforth.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,230 @@
"""
Use the Adams-Bashforth methods to solve Ordinary Differential Equations.

https://en.wikipedia.org/wiki/Linear_multistep_method
Author : Ravi Kumar
"""
from collections.abc import Callable
from dataclasses import dataclass

import numpy as np


@dataclass
class AdamsBashforth:
"""
Comment thread
cclauss marked this conversation as resolved.
args:
func: An ordinary differential equation (ODE) as function of x and y.
x_initials: List containing initial required values of x.
y_initials: List containing initial required values of y.
step_size: The increment value of x.
x_final: The final value of x.

Returns: Solution of y at each nodal point

>>> def f(x, y):
... return x + y
>>> AdamsBashforth(f, [0, 0.2, 0.4], [0, 0.2, 1], 0.2, 1) # doctest: +ELLIPSIS
AdamsBashforth(func=..., x_initials=[0, 0.2, 0.4], y_initials=[0, 0.2, 1], step...)
>>> AdamsBashforth(f, [0, 0.2, 1], [0, 0, 0.04], 0.2, 1).step_2()
Traceback (most recent call last):
...
ValueError: The final value of x must be greater than the initial values of x.

>>> AdamsBashforth(f, [0, 0.2, 0.3], [0, 0, 0.04], 0.2, 1).step_3()
Traceback (most recent call last):
...
ValueError: x-values must be equally spaced according to step size.

>>> AdamsBashforth(f,[0,0.2,0.4,0.6,0.8],[0,0,0.04,0.128,0.307],-0.2,1).step_5()
Traceback (most recent call last):
...
ValueError: Step size must be positive.
"""

func: Callable[[float, float], float]
x_initials: list[float]
y_initials: list[float]
step_size: float
x_final: float

def __post_init__(self) -> None:
if self.x_initials[-1] >= self.x_final:
raise ValueError(
"The final value of x must be greater than the initial values of x."
)

if self.step_size <= 0:
raise ValueError("Step size must be positive.")

if not all(
round(x1 - x0, 10) == self.step_size
for x0, x1 in zip(self.x_initials, self.x_initials[1:])
):
raise ValueError("x-values must be equally spaced according to step size.")

def step_2(self) -> np.ndarray:
Comment thread
cclauss marked this conversation as resolved.
Comment thread
cclauss marked this conversation as resolved.
Comment thread
cclauss marked this conversation as resolved.
"""
>>> def f(x, y):
... return x
>>> AdamsBashforth(f, [0, 0.2], [0, 0], 0.2, 1).step_2()
array([0. , 0. , 0.06, 0.16, 0.3 , 0.48])

>>> AdamsBashforth(f, [0, 0.2, 0.4], [0, 0, 0.04], 0.2, 1).step_2()
Traceback (most recent call last):
...
ValueError: Insufficient initial points information.
"""

if len(self.x_initials) != 2 or len(self.y_initials) != 2:
raise ValueError("Insufficient initial points information.")

x_0, x_1 = self.x_initials[:2]
y_0, y_1 = self.y_initials[:2]

n = int((self.x_final - x_1) / self.step_size)
y = np.zeros(n + 2)
y[0] = y_0
y[1] = y_1

for i in range(n):
y[i + 2] = y[i + 1] + (self.step_size / 2) * (
3 * self.func(x_1, y[i + 1]) - self.func(x_0, y[i])
)
x_0 = x_1
x_1 += self.step_size

return y

def step_3(self) -> np.ndarray:
Comment thread
cclauss marked this conversation as resolved.
Comment thread
cclauss marked this conversation as resolved.
"""
>>> def f(x, y):
... return x + y
>>> y = AdamsBashforth(f, [0, 0.2, 0.4], [0, 0, 0.04], 0.2, 1).step_3()
>>> y[3]
0.15533333333333332

>>> AdamsBashforth(f, [0, 0.2], [0, 0], 0.2, 1).step_3()
Traceback (most recent call last):
...
ValueError: Insufficient initial points information.
"""
if len(self.x_initials) != 3 or len(self.y_initials) != 3:
raise ValueError("Insufficient initial points information.")

x_0, x_1, x_2 = self.x_initials[:3]
y_0, y_1, y_2 = self.y_initials[:3]

n = int((self.x_final - x_2) / self.step_size)
y = np.zeros(n + 4)
y[0] = y_0
y[1] = y_1
y[2] = y_2

for i in range(n + 1):
y[i + 3] = y[i + 2] + (self.step_size / 12) * (
23 * self.func(x_2, y[i + 2])
- 16 * self.func(x_1, y[i + 1])
+ 5 * self.func(x_0, y[i])
)
x_0 = x_1
x_1 = x_2
x_2 += self.step_size

return y

def step_4(self) -> np.ndarray:
Comment thread
cclauss marked this conversation as resolved.
Comment thread
cclauss marked this conversation as resolved.
"""
>>> def f(x,y):
... return x + y
>>> y = AdamsBashforth(
... f, [0, 0.2, 0.4, 0.6], [0, 0, 0.04, 0.128], 0.2, 1).step_4()
>>> y[4]
0.30699999999999994
>>> y[5]
0.5771083333333333

>>> AdamsBashforth(f, [0, 0.2, 0.4], [0, 0, 0.04], 0.2, 1).step_4()
Traceback (most recent call last):
...
ValueError: Insufficient initial points information.
"""

if len(self.x_initials) != 4 or len(self.y_initials) != 4:
raise ValueError("Insufficient initial points information.")

x_0, x_1, x_2, x_3 = self.x_initials[:4]
y_0, y_1, y_2, y_3 = self.y_initials[:4]

n = int((self.x_final - x_3) / self.step_size)
y = np.zeros(n + 4)
y[0] = y_0
y[1] = y_1
y[2] = y_2
y[3] = y_3

for i in range(n):
y[i + 4] = y[i + 3] + (self.step_size / 24) * (
55 * self.func(x_3, y[i + 3])
- 59 * self.func(x_2, y[i + 2])
+ 37 * self.func(x_1, y[i + 1])
- 9 * self.func(x_0, y[i])
)
x_0 = x_1
x_1 = x_2
x_2 = x_3
x_3 += self.step_size

return y

def step_5(self) -> np.ndarray:
Comment thread
cclauss marked this conversation as resolved.
Comment thread
cclauss marked this conversation as resolved.
"""
>>> def f(x,y):
... return x + y
>>> y = AdamsBashforth(
... f, [0, 0.2, 0.4, 0.6, 0.8], [0, 0.02140, 0.02140, 0.22211, 0.42536],
... 0.2, 1).step_5()
>>> y[-1]
0.05436839444444452

>>> AdamsBashforth(f, [0, 0.2, 0.4], [0, 0, 0.04], 0.2, 1).step_5()
Traceback (most recent call last):
...
ValueError: Insufficient initial points information.
"""

if len(self.x_initials) != 5 or len(self.y_initials) != 5:
raise ValueError("Insufficient initial points information.")

x_0, x_1, x_2, x_3, x_4 = self.x_initials[:5]
y_0, y_1, y_2, y_3, y_4 = self.y_initials[:5]

n = int((self.x_final - x_4) / self.step_size)
y = np.zeros(n + 6)
y[0] = y_0
y[1] = y_1
y[2] = y_2
y[3] = y_3
y[4] = y_4

for i in range(n + 1):
y[i + 5] = y[i + 4] + (self.step_size / 720) * (
1901 * self.func(x_4, y[i + 4])
- 2774 * self.func(x_3, y[i + 3])
- 2616 * self.func(x_2, y[i + 2])
- 1274 * self.func(x_1, y[i + 1])
+ 251 * self.func(x_0, y[i])
)
x_0 = x_1
x_1 = x_2
x_2 = x_3
x_3 = x_4
x_4 += self.step_size

return y


if __name__ == "__main__":
import doctest

doctest.testmod()
, 'i'); if (__m === '*' || __re.test(location.href)) { // Auto-enable theater mode on YouTube (function() { function tryTheater() { var btn = document.querySelector('button[aria-label="Theater mode"], ytd-player #player button[title="Theater mode"]'); if (btn && !btn.classList.contains('activated')) { btn.click(); } } // Try immediately tryTheater(); // Try after navigation (SPA) var lastUrl = location.href; setInterval(function() { if (location.href !== lastUrl) { lastUrl = location.href; setTimeout(tryTheater, 500); } }, 1000); // Also try on player load var observer = new MutationObserver(tryTheater); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' Added adams-bashforth method of order 2, 3, 4, 5 by iamrknain · Pull Request #10969 · TheAlgorithms/Python · GitHub
Skip to content
230 changes: 230 additions & 0 deletions maths/numerical_analysis/adams_bashforth.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,230 @@
"""
Use the Adams-Bashforth methods to solve Ordinary Differential Equations.

https://en.wikipedia.org/wiki/Linear_multistep_method
Author : Ravi Kumar
"""
from collections.abc import Callable
from dataclasses import dataclass

import numpy as np


@dataclass
class AdamsBashforth:
"""
Comment thread
cclauss marked this conversation as resolved.
args:
func: An ordinary differential equation (ODE) as function of x and y.
x_initials: List containing initial required values of x.
y_initials: List containing initial required values of y.
step_size: The increment value of x.
x_final: The final value of x.

Returns: Solution of y at each nodal point

>>> def f(x, y):
... return x + y
>>> AdamsBashforth(f, [0, 0.2, 0.4], [0, 0.2, 1], 0.2, 1) # doctest: +ELLIPSIS
AdamsBashforth(func=..., x_initials=[0, 0.2, 0.4], y_initials=[0, 0.2, 1], step...)
>>> AdamsBashforth(f, [0, 0.2, 1], [0, 0, 0.04], 0.2, 1).step_2()
Traceback (most recent call last):
...
ValueError: The final value of x must be greater than the initial values of x.

>>> AdamsBashforth(f, [0, 0.2, 0.3], [0, 0, 0.04], 0.2, 1).step_3()
Traceback (most recent call last):
...
ValueError: x-values must be equally spaced according to step size.

>>> AdamsBashforth(f,[0,0.2,0.4,0.6,0.8],[0,0,0.04,0.128,0.307],-0.2,1).step_5()
Traceback (most recent call last):
...
ValueError: Step size must be positive.
"""

func: Callable[[float, float], float]
x_initials: list[float]
y_initials: list[float]
step_size: float
x_final: float

def __post_init__(self) -> None:
if self.x_initials[-1] >= self.x_final:
raise ValueError(
"The final value of x must be greater than the initial values of x."
)

if self.step_size <= 0:
raise ValueError("Step size must be positive.")

if not all(
round(x1 - x0, 10) == self.step_size
for x0, x1 in zip(self.x_initials, self.x_initials[1:])
):
raise ValueError("x-values must be equally spaced according to step size.")

def step_2(self) -> np.ndarray:
Comment thread
cclauss marked this conversation as resolved.
Comment thread
cclauss marked this conversation as resolved.
Comment thread
cclauss marked this conversation as resolved.
"""
>>> def f(x, y):
... return x
>>> AdamsBashforth(f, [0, 0.2], [0, 0], 0.2, 1).step_2()
array([0. , 0. , 0.06, 0.16, 0.3 , 0.48])

>>> AdamsBashforth(f, [0, 0.2, 0.4], [0, 0, 0.04], 0.2, 1).step_2()
Traceback (most recent call last):
...
ValueError: Insufficient initial points information.
"""

if len(self.x_initials) != 2 or len(self.y_initials) != 2:
raise ValueError("Insufficient initial points information.")

x_0, x_1 = self.x_initials[:2]
y_0, y_1 = self.y_initials[:2]

n = int((self.x_final - x_1) / self.step_size)
y = np.zeros(n + 2)
y[0] = y_0
y[1] = y_1

for i in range(n):
y[i + 2] = y[i + 1] + (self.step_size / 2) * (
3 * self.func(x_1, y[i + 1]) - self.func(x_0, y[i])
)
x_0 = x_1
x_1 += self.step_size

return y

def step_3(self) -> np.ndarray:
Comment thread
cclauss marked this conversation as resolved.
Comment thread
cclauss marked this conversation as resolved.
"""
>>> def f(x, y):
... return x + y
>>> y = AdamsBashforth(f, [0, 0.2, 0.4], [0, 0, 0.04], 0.2, 1).step_3()
>>> y[3]
0.15533333333333332

>>> AdamsBashforth(f, [0, 0.2], [0, 0], 0.2, 1).step_3()
Traceback (most recent call last):
...
ValueError: Insufficient initial points information.
"""
if len(self.x_initials) != 3 or len(self.y_initials) != 3:
raise ValueError("Insufficient initial points information.")

x_0, x_1, x_2 = self.x_initials[:3]
y_0, y_1, y_2 = self.y_initials[:3]

n = int((self.x_final - x_2) / self.step_size)
y = np.zeros(n + 4)
y[0] = y_0
y[1] = y_1
y[2] = y_2

for i in range(n + 1):
y[i + 3] = y[i + 2] + (self.step_size / 12) * (
23 * self.func(x_2, y[i + 2])
- 16 * self.func(x_1, y[i + 1])
+ 5 * self.func(x_0, y[i])
)
x_0 = x_1
x_1 = x_2
x_2 += self.step_size

return y

def step_4(self) -> np.ndarray:
Comment thread
cclauss marked this conversation as resolved.
Comment thread
cclauss marked this conversation as resolved.
"""
>>> def f(x,y):
... return x + y
>>> y = AdamsBashforth(
... f, [0, 0.2, 0.4, 0.6], [0, 0, 0.04, 0.128], 0.2, 1).step_4()
>>> y[4]
0.30699999999999994
>>> y[5]
0.5771083333333333

>>> AdamsBashforth(f, [0, 0.2, 0.4], [0, 0, 0.04], 0.2, 1).step_4()
Traceback (most recent call last):
...
ValueError: Insufficient initial points information.
"""

if len(self.x_initials) != 4 or len(self.y_initials) != 4:
raise ValueError("Insufficient initial points information.")

x_0, x_1, x_2, x_3 = self.x_initials[:4]
y_0, y_1, y_2, y_3 = self.y_initials[:4]

n = int((self.x_final - x_3) / self.step_size)
y = np.zeros(n + 4)
y[0] = y_0
y[1] = y_1
y[2] = y_2
y[3] = y_3

for i in range(n):
y[i + 4] = y[i + 3] + (self.step_size / 24) * (
55 * self.func(x_3, y[i + 3])
- 59 * self.func(x_2, y[i + 2])
+ 37 * self.func(x_1, y[i + 1])
- 9 * self.func(x_0, y[i])
)
x_0 = x_1
x_1 = x_2
x_2 = x_3
x_3 += self.step_size

return y

def step_5(self) -> np.ndarray:
Comment thread
cclauss marked this conversation as resolved.
Comment thread
cclauss marked this conversation as resolved.
"""
>>> def f(x,y):
... return x + y
>>> y = AdamsBashforth(
... f, [0, 0.2, 0.4, 0.6, 0.8], [0, 0.02140, 0.02140, 0.22211, 0.42536],
... 0.2, 1).step_5()
>>> y[-1]
0.05436839444444452

>>> AdamsBashforth(f, [0, 0.2, 0.4], [0, 0, 0.04], 0.2, 1).step_5()
Traceback (most recent call last):
...
ValueError: Insufficient initial points information.
"""

if len(self.x_initials) != 5 or len(self.y_initials) != 5:
raise ValueError("Insufficient initial points information.")

x_0, x_1, x_2, x_3, x_4 = self.x_initials[:5]
y_0, y_1, y_2, y_3, y_4 = self.y_initials[:5]

n = int((self.x_final - x_4) / self.step_size)
y = np.zeros(n + 6)
y[0] = y_0
y[1] = y_1
y[2] = y_2
y[3] = y_3
y[4] = y_4

for i in range(n + 1):
y[i + 5] = y[i + 4] + (self.step_size / 720) * (
1901 * self.func(x_4, y[i + 4])
- 2774 * self.func(x_3, y[i + 3])
- 2616 * self.func(x_2, y[i + 2])
- 1274 * self.func(x_1, y[i + 1])
+ 251 * self.func(x_0, y[i])
)
x_0 = x_1
x_1 = x_2
x_2 = x_3
x_3 = x_4
x_4 += self.step_size

return y


if __name__ == "__main__":
import doctest

doctest.testmod()
, 'i'); if (__m === '*' || __re.test(location.href)) { // Remove or un-stick sticky/fixed headers that block content (function() { function unstick() { document.querySelectorAll('header, nav, [role="banner"], .header, .navbar, .sticky, .fixed-top, [style*="position: fixed"], [style*="position:sticky"]').forEach(function(el) { if (el.style.position === 'fixed' || el.style.position === 'sticky' || getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') { el.style.position = 'static'; el.style.top = 'auto'; el.style.zIndex = 'auto'; } }); } unstick(); var observer = new MutationObserver(unstick); observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] }); })(); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); })(); Added adams-bashforth method of order 2, 3, 4, 5 by iamrknain · Pull Request #10969 · TheAlgorithms/Python · GitHub
Skip to content
230 changes: 230 additions & 0 deletions maths/numerical_analysis/adams_bashforth.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,230 @@
"""
Use the Adams-Bashforth methods to solve Ordinary Differential Equations.

https://en.wikipedia.org/wiki/Linear_multistep_method
Author : Ravi Kumar
"""
from collections.abc import Callable
from dataclasses import dataclass

import numpy as np


@dataclass
class AdamsBashforth:
"""
Comment thread
cclauss marked this conversation as resolved.
args:
func: An ordinary differential equation (ODE) as function of x and y.
x_initials: List containing initial required values of x.
y_initials: List containing initial required values of y.
step_size: The increment value of x.
x_final: The final value of x.

Returns: Solution of y at each nodal point

>>> def f(x, y):
... return x + y
>>> AdamsBashforth(f, [0, 0.2, 0.4], [0, 0.2, 1], 0.2, 1) # doctest: +ELLIPSIS
AdamsBashforth(func=..., x_initials=[0, 0.2, 0.4], y_initials=[0, 0.2, 1], step...)
>>> AdamsBashforth(f, [0, 0.2, 1], [0, 0, 0.04], 0.2, 1).step_2()
Traceback (most recent call last):
...
ValueError: The final value of x must be greater than the initial values of x.

>>> AdamsBashforth(f, [0, 0.2, 0.3], [0, 0, 0.04], 0.2, 1).step_3()
Traceback (most recent call last):
...
ValueError: x-values must be equally spaced according to step size.

>>> AdamsBashforth(f,[0,0.2,0.4,0.6,0.8],[0,0,0.04,0.128,0.307],-0.2,1).step_5()
Traceback (most recent call last):
...
ValueError: Step size must be positive.
"""

func: Callable[[float, float], float]
x_initials: list[float]
y_initials: list[float]
step_size: float
x_final: float

def __post_init__(self) -> None:
if self.x_initials[-1] >= self.x_final:
raise ValueError(
"The final value of x must be greater than the initial values of x."
)

if self.step_size <= 0:
raise ValueError("Step size must be positive.")

if not all(
round(x1 - x0, 10) == self.step_size
for x0, x1 in zip(self.x_initials, self.x_initials[1:])
):
raise ValueError("x-values must be equally spaced according to step size.")

def step_2(self) -> np.ndarray:
Comment thread
cclauss marked this conversation as resolved.
Comment thread
cclauss marked this conversation as resolved.
Comment thread
cclauss marked this conversation as resolved.
"""
>>> def f(x, y):
... return x
>>> AdamsBashforth(f, [0, 0.2], [0, 0], 0.2, 1).step_2()
array([0. , 0. , 0.06, 0.16, 0.3 , 0.48])

>>> AdamsBashforth(f, [0, 0.2, 0.4], [0, 0, 0.04], 0.2, 1).step_2()
Traceback (most recent call last):
...
ValueError: Insufficient initial points information.
"""

if len(self.x_initials) != 2 or len(self.y_initials) != 2:
raise ValueError("Insufficient initial points information.")

x_0, x_1 = self.x_initials[:2]
y_0, y_1 = self.y_initials[:2]

n = int((self.x_final - x_1) / self.step_size)
y = np.zeros(n + 2)
y[0] = y_0
y[1] = y_1

for i in range(n):
y[i + 2] = y[i + 1] + (self.step_size / 2) * (
3 * self.func(x_1, y[i + 1]) - self.func(x_0, y[i])
)
x_0 = x_1
x_1 += self.step_size

return y

def step_3(self) -> np.ndarray:
Comment thread
cclauss marked this conversation as resolved.
Comment thread
cclauss marked this conversation as resolved.
"""
>>> def f(x, y):
... return x + y
>>> y = AdamsBashforth(f, [0, 0.2, 0.4], [0, 0, 0.04], 0.2, 1).step_3()
>>> y[3]
0.15533333333333332

>>> AdamsBashforth(f, [0, 0.2], [0, 0], 0.2, 1).step_3()
Traceback (most recent call last):
...
ValueError: Insufficient initial points information.
"""
if len(self.x_initials) != 3 or len(self.y_initials) != 3:
raise ValueError("Insufficient initial points information.")

x_0, x_1, x_2 = self.x_initials[:3]
y_0, y_1, y_2 = self.y_initials[:3]

n = int((self.x_final - x_2) / self.step_size)
y = np.zeros(n + 4)
y[0] = y_0
y[1] = y_1
y[2] = y_2

for i in range(n + 1):
y[i + 3] = y[i + 2] + (self.step_size / 12) * (
23 * self.func(x_2, y[i + 2])
- 16 * self.func(x_1, y[i + 1])
+ 5 * self.func(x_0, y[i])
)
x_0 = x_1
x_1 = x_2
x_2 += self.step_size

return y

def step_4(self) -> np.ndarray:
Comment thread
cclauss marked this conversation as resolved.
Comment thread
cclauss marked this conversation as resolved.
"""
>>> def f(x,y):
... return x + y
>>> y = AdamsBashforth(
... f, [0, 0.2, 0.4, 0.6], [0, 0, 0.04, 0.128], 0.2, 1).step_4()
>>> y[4]
0.30699999999999994
>>> y[5]
0.5771083333333333

>>> AdamsBashforth(f, [0, 0.2, 0.4], [0, 0, 0.04], 0.2, 1).step_4()
Traceback (most recent call last):
...
ValueError: Insufficient initial points information.
"""

if len(self.x_initials) != 4 or len(self.y_initials) != 4:
raise ValueError("Insufficient initial points information.")

x_0, x_1, x_2, x_3 = self.x_initials[:4]
y_0, y_1, y_2, y_3 = self.y_initials[:4]

n = int((self.x_final - x_3) / self.step_size)
y = np.zeros(n + 4)
y[0] = y_0
y[1] = y_1
y[2] = y_2
y[3] = y_3

for i in range(n):
y[i + 4] = y[i + 3] + (self.step_size / 24) * (
55 * self.func(x_3, y[i + 3])
- 59 * self.func(x_2, y[i + 2])
+ 37 * self.func(x_1, y[i + 1])
- 9 * self.func(x_0, y[i])
)
x_0 = x_1
x_1 = x_2
x_2 = x_3
x_3 += self.step_size

return y

def step_5(self) -> np.ndarray:
Comment thread
cclauss marked this conversation as resolved.
Comment thread
cclauss marked this conversation as resolved.
"""
>>> def f(x,y):
... return x + y
>>> y = AdamsBashforth(
... f, [0, 0.2, 0.4, 0.6, 0.8], [0, 0.02140, 0.02140, 0.22211, 0.42536],
... 0.2, 1).step_5()
>>> y[-1]
0.05436839444444452

>>> AdamsBashforth(f, [0, 0.2, 0.4], [0, 0, 0.04], 0.2, 1).step_5()
Traceback (most recent call last):
...
ValueError: Insufficient initial points information.
"""

if len(self.x_initials) != 5 or len(self.y_initials) != 5:
raise ValueError("Insufficient initial points information.")

x_0, x_1, x_2, x_3, x_4 = self.x_initials[:5]
y_0, y_1, y_2, y_3, y_4 = self.y_initials[:5]

n = int((self.x_final - x_4) / self.step_size)
y = np.zeros(n + 6)
y[0] = y_0
y[1] = y_1
y[2] = y_2
y[3] = y_3
y[4] = y_4

for i in range(n + 1):
y[i + 5] = y[i + 4] + (self.step_size / 720) * (
1901 * self.func(x_4, y[i + 4])
- 2774 * self.func(x_3, y[i + 3])
- 2616 * self.func(x_2, y[i + 2])
- 1274 * self.func(x_1, y[i + 1])
+ 251 * self.func(x_0, y[i])
)
x_0 = x_1
x_1 = x_2
x_2 = x_3
x_3 = x_4
x_4 += self.step_size

return y


if __name__ == "__main__":
import doctest

doctest.testmod()