Skip to content

Commit

Permalink
fix: format new code
Browse files Browse the repository at this point in the history
  • Loading branch information
vil02 committed Jan 6, 2024
1 parent af217e8 commit 89024c6
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 10 deletions.
18 changes: 12 additions & 6 deletions src/math/runge_kutta_integration.jl
Original file line number Diff line number Diff line change
Expand Up @@ -58,19 +58,25 @@ julia> exp.([0.0, 0.1])
# Contributors:
- [E-W-Jones](https://github.com/E-W-Jones)
"""
function runge_kutta_integration(f::Function, x0::Real, y0::Real, h::Real, x_stop::Real)
function runge_kutta_integration(
f::Function,
x0::Real,
y0::Real,
h::Real,
x_stop::Real,
)
h > 0 || throw(DomainError(h, "The step size `h` should be >0."))

x = Float64(x0)
y = Float64(y0)
output_x = [x]
output_y = [y]

while x < x_stop
k1 = f(x, y)
k2 = f(x + h/2, y + k1*h/2)
k3 = f(x + h/2, y + k2*h/2)
k4 = f(x + h , y + k3*h )
k2 = f(x + h / 2, y + k1 * h / 2)
k3 = f(x + h / 2, y + k2 * h / 2)
k4 = f(x + h, y + k3 * h)

y += h * (k1 + 2k2 + 2k3 + k4) / 6
x += h
Expand All @@ -80,4 +86,4 @@ function runge_kutta_integration(f::Function, x0::Real, y0::Real, h::Real, x_sto
end

return output_x, output_y
end
end
16 changes: 12 additions & 4 deletions test/math.jl
Original file line number Diff line number Diff line change
Expand Up @@ -378,12 +378,20 @@ using TheAlgorithms.Math
end

@testset "Math: Runge_Kutta Integration" begin
@test runge_kutta_integration((x, y)->1, 0, 0, 1, 3) == ([0.0, 1.0, 2.0, 3.0], [0.0, 1.0, 2.0, 3.0])
@test runge_kutta_integration((x, y) -> 1, 0, 0, 1, 3) ==
([0.0, 1.0, 2.0, 3.0], [0.0, 1.0, 2.0, 3.0])
@test begin
x, y = runge_kutta_integration((x, y)->cos(x), 0, 0, 1e-4, π/2)
isapprox(x[end], π/2; rtol=1e-4) && isapprox(y[end], 1; rtol=1e-4)
x, y = runge_kutta_integration((x, y) -> cos(x), 0, 0, 1e-4, π / 2)
isapprox(x[end], π / 2; rtol = 1e-4) &&
isapprox(y[end], 1; rtol = 1e-4)
end
@test_throws DomainError runge_kutta_integration((x, y)->(), 0, 0, 0, 0)
@test_throws DomainError runge_kutta_integration(
(x, y) -> (),
0,
0,
0,
0,
)
end

@testset "Math: Sum of Arithmetic progression" begin
Expand Down

0 comments on commit 89024c6

Please sign in to comment.